bp2build.go 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897
  1. // Copyright 2021 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 cc
  15. import (
  16. "fmt"
  17. "path/filepath"
  18. "strings"
  19. "sync"
  20. "android/soong/android"
  21. "android/soong/bazel"
  22. "android/soong/cc/config"
  23. "github.com/google/blueprint"
  24. "github.com/google/blueprint/proptools"
  25. )
  26. const (
  27. cSrcPartition = "c"
  28. asSrcPartition = "as"
  29. asmSrcPartition = "asm"
  30. lSrcPartition = "l"
  31. llSrcPartition = "ll"
  32. cppSrcPartition = "cpp"
  33. protoSrcPartition = "proto"
  34. aidlSrcPartition = "aidl"
  35. syspropSrcPartition = "sysprop"
  36. yaccSrcPartition = "yacc"
  37. rScriptSrcPartition = "renderScript"
  38. stubsSuffix = "_stub_libs_current"
  39. )
  40. // staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
  41. // properties which apply to either the shared or static version of a cc_library module.
  42. type staticOrSharedAttributes struct {
  43. Srcs bazel.LabelListAttribute
  44. Srcs_c bazel.LabelListAttribute
  45. Srcs_as bazel.LabelListAttribute
  46. Srcs_aidl bazel.LabelListAttribute
  47. Hdrs bazel.LabelListAttribute
  48. Copts bazel.StringListAttribute
  49. Deps bazel.LabelListAttribute
  50. Implementation_deps bazel.LabelListAttribute
  51. Dynamic_deps bazel.LabelListAttribute
  52. Implementation_dynamic_deps bazel.LabelListAttribute
  53. Whole_archive_deps bazel.LabelListAttribute
  54. Implementation_whole_archive_deps bazel.LabelListAttribute
  55. Runtime_deps bazel.LabelListAttribute
  56. System_dynamic_deps bazel.LabelListAttribute
  57. Enabled bazel.BoolAttribute
  58. Native_coverage *bool
  59. Apex_available []string
  60. Features bazel.StringListAttribute
  61. sdkAttributes
  62. tidyAttributes
  63. }
  64. type tidyAttributes struct {
  65. Tidy *string
  66. Tidy_flags []string
  67. Tidy_checks []string
  68. Tidy_checks_as_errors []string
  69. Tidy_disabled_srcs bazel.LabelListAttribute
  70. Tidy_timeout_srcs bazel.LabelListAttribute
  71. }
  72. func (m *Module) convertTidyAttributes(ctx android.BaseMutatorContext, moduleAttrs *tidyAttributes) {
  73. for _, f := range m.features {
  74. if tidy, ok := f.(*tidyFeature); ok {
  75. var tidyAttr *string
  76. if tidy.Properties.Tidy != nil {
  77. if *tidy.Properties.Tidy {
  78. tidyAttr = proptools.StringPtr("local")
  79. } else {
  80. tidyAttr = proptools.StringPtr("never")
  81. }
  82. }
  83. moduleAttrs.Tidy = tidyAttr
  84. moduleAttrs.Tidy_flags = tidy.Properties.Tidy_flags
  85. moduleAttrs.Tidy_checks = tidy.Properties.Tidy_checks
  86. moduleAttrs.Tidy_checks_as_errors = tidy.Properties.Tidy_checks_as_errors
  87. }
  88. }
  89. archVariantProps := m.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
  90. for axis, configToProps := range archVariantProps {
  91. for cfg, _props := range configToProps {
  92. if archProps, ok := _props.(*BaseCompilerProperties); ok {
  93. archDisabledSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_disabled_srcs)
  94. moduleAttrs.Tidy_disabled_srcs.SetSelectValue(axis, cfg, archDisabledSrcs)
  95. archTimeoutSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_timeout_srcs)
  96. moduleAttrs.Tidy_timeout_srcs.SetSelectValue(axis, cfg, archTimeoutSrcs)
  97. }
  98. }
  99. }
  100. }
  101. // groupSrcsByExtension partitions `srcs` into groups based on file extension.
  102. func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
  103. // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
  104. // macro.
  105. addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
  106. return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
  107. m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
  108. labelStr := label.Label
  109. if !exists || !android.IsFilegroup(otherModuleCtx, m) {
  110. return labelStr, false
  111. }
  112. // If the filegroup is already converted to aidl_library or proto_library,
  113. // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
  114. fg, _ := m.(android.FileGroupAsLibrary)
  115. if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
  116. return labelStr, false
  117. }
  118. return labelStr + suffix, true
  119. }
  120. }
  121. // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
  122. labels := bazel.LabelPartitions{
  123. protoSrcPartition: android.ProtoSrcLabelPartition,
  124. cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
  125. asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
  126. asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
  127. aidlSrcPartition: android.AidlSrcLabelPartition,
  128. // TODO(http://b/231968910): If there is ever a filegroup target that
  129. // contains .l or .ll files we will need to find a way to add a
  130. // LabelMapper for these that identifies these filegroups and
  131. // converts them appropriately
  132. lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
  133. llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
  134. rScriptSrcPartition: bazel.LabelPartition{Extensions: []string{".fs", ".rscript"}},
  135. // C++ is the "catch-all" group, and comprises generated sources because we don't
  136. // know the language of these sources until the genrule is executed.
  137. cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
  138. syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
  139. yaccSrcPartition: bazel.LabelPartition{Extensions: []string{".y", "yy"}},
  140. }
  141. return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
  142. }
  143. // bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
  144. func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
  145. lib, ok := module.compiler.(*libraryDecorator)
  146. if !ok {
  147. return staticOrSharedAttributes{}
  148. }
  149. return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
  150. }
  151. // bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
  152. func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
  153. return bp2BuildParseLibProps(ctx, module, false)
  154. }
  155. // bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
  156. func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
  157. return bp2BuildParseLibProps(ctx, module, true)
  158. }
  159. type depsPartition struct {
  160. export bazel.LabelList
  161. implementation bazel.LabelList
  162. }
  163. type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
  164. func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
  165. if !exportsDeps {
  166. return depsPartition{
  167. implementation: fn(ctx, allDeps),
  168. }
  169. }
  170. implementation, export := android.FilterList(allDeps, exportedDeps)
  171. return depsPartition{
  172. export: fn(ctx, export),
  173. implementation: fn(ctx, implementation),
  174. }
  175. }
  176. type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
  177. func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
  178. if !exportsDeps {
  179. return depsPartition{
  180. implementation: fn(ctx, allDeps, excludes),
  181. }
  182. }
  183. implementation, export := android.FilterList(allDeps, exportedDeps)
  184. return depsPartition{
  185. export: fn(ctx, export, excludes),
  186. implementation: fn(ctx, implementation, excludes),
  187. }
  188. }
  189. func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
  190. for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
  191. for cfg, props := range configToProps {
  192. parseFunc(axis, cfg, props)
  193. }
  194. }
  195. }
  196. // Parses properties common to static and shared libraries. Also used for prebuilt libraries.
  197. func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
  198. attrs := staticOrSharedAttributes{}
  199. setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
  200. attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutHiddenVisibility))
  201. attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
  202. attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
  203. staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
  204. attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
  205. attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
  206. sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
  207. attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
  208. attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
  209. attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
  210. attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
  211. }
  212. // system_dynamic_deps distinguishes between nil/empty list behavior:
  213. // nil -> use default values
  214. // empty list -> no values specified
  215. attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
  216. var apexAvailable []string
  217. if isStatic {
  218. apexAvailable = lib.StaticProperties.Static.Apex_available
  219. bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  220. if staticOrSharedProps, ok := props.(*StaticProperties); ok {
  221. setAttrs(axis, config, staticOrSharedProps.Static)
  222. }
  223. })
  224. } else {
  225. apexAvailable = lib.SharedProperties.Shared.Apex_available
  226. bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  227. if staticOrSharedProps, ok := props.(*SharedProperties); ok {
  228. setAttrs(axis, config, staticOrSharedProps.Shared)
  229. }
  230. })
  231. }
  232. partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
  233. attrs.Srcs = partitionedSrcs[cppSrcPartition]
  234. attrs.Srcs_c = partitionedSrcs[cSrcPartition]
  235. attrs.Srcs_as = partitionedSrcs[asSrcPartition]
  236. attrs.Apex_available = android.ConvertApexAvailableToTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), apexAvailable)
  237. attrs.Features.Append(convertHiddenVisibilityToFeatureStaticOrShared(ctx, module, isStatic))
  238. if !partitionedSrcs[protoSrcPartition].IsEmpty() {
  239. // TODO(b/208815215): determine whether this is used and add support if necessary
  240. ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
  241. }
  242. return attrs
  243. }
  244. // Convenience struct to hold all attributes parsed from prebuilt properties.
  245. type prebuiltAttributes struct {
  246. Src bazel.LabelAttribute
  247. Enabled bazel.BoolAttribute
  248. }
  249. func parseSrc(ctx android.BazelConversionPathContext, srcLabelAttribute *bazel.LabelAttribute, axis bazel.ConfigurationAxis, config string, srcs []string) {
  250. srcFileError := func() {
  251. ctx.ModuleErrorf("parseSrc: Expected at most one source file for %s %s\n", axis, config)
  252. }
  253. if len(srcs) > 1 {
  254. srcFileError()
  255. return
  256. } else if len(srcs) == 0 {
  257. return
  258. }
  259. if srcLabelAttribute.SelectValue(axis, config) != nil {
  260. srcFileError()
  261. return
  262. }
  263. srcLabelAttribute.SetSelectValue(axis, config, android.BazelLabelForModuleSrcSingle(ctx, srcs[0]))
  264. }
  265. // NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
  266. func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) prebuiltAttributes {
  267. var srcLabelAttribute bazel.LabelAttribute
  268. bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  269. if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
  270. parseSrc(ctx, &srcLabelAttribute, axis, config, prebuiltLinkerProperties.Srcs)
  271. }
  272. })
  273. var enabledLabelAttribute bazel.BoolAttribute
  274. parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
  275. if props.Enabled != nil {
  276. enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
  277. }
  278. parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
  279. }
  280. if isStatic {
  281. bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  282. if staticProperties, ok := props.(*StaticProperties); ok {
  283. parseAttrs(axis, config, staticProperties.Static)
  284. }
  285. })
  286. } else {
  287. bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  288. if sharedProperties, ok := props.(*SharedProperties); ok {
  289. parseAttrs(axis, config, sharedProperties.Shared)
  290. }
  291. })
  292. }
  293. return prebuiltAttributes{
  294. Src: srcLabelAttribute,
  295. Enabled: enabledLabelAttribute,
  296. }
  297. }
  298. func bp2BuildParsePrebuiltBinaryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
  299. var srcLabelAttribute bazel.LabelAttribute
  300. bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  301. if props, ok := props.(*prebuiltLinkerProperties); ok {
  302. parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
  303. }
  304. })
  305. return prebuiltAttributes{
  306. Src: srcLabelAttribute,
  307. }
  308. }
  309. func bp2BuildParsePrebuiltObjectProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
  310. var srcLabelAttribute bazel.LabelAttribute
  311. bp2BuildPropParseHelper(ctx, module, &prebuiltObjectProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  312. if props, ok := props.(*prebuiltObjectProperties); ok {
  313. parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
  314. }
  315. })
  316. return prebuiltAttributes{
  317. Src: srcLabelAttribute,
  318. }
  319. }
  320. type baseAttributes struct {
  321. compilerAttributes
  322. linkerAttributes
  323. // A combination of compilerAttributes.features and linkerAttributes.features, as well as sanitizer features
  324. features bazel.StringListAttribute
  325. protoDependency *bazel.LabelAttribute
  326. aidlDependency *bazel.LabelAttribute
  327. Native_coverage *bool
  328. }
  329. // Convenience struct to hold all attributes parsed from compiler properties.
  330. type compilerAttributes struct {
  331. // Options for all languages
  332. copts bazel.StringListAttribute
  333. // Assembly options and sources
  334. asFlags bazel.StringListAttribute
  335. asSrcs bazel.LabelListAttribute
  336. asmSrcs bazel.LabelListAttribute
  337. // C options and sources
  338. conlyFlags bazel.StringListAttribute
  339. cSrcs bazel.LabelListAttribute
  340. // C++ options and sources
  341. cppFlags bazel.StringListAttribute
  342. srcs bazel.LabelListAttribute
  343. // Lex sources and options
  344. lSrcs bazel.LabelListAttribute
  345. llSrcs bazel.LabelListAttribute
  346. lexopts bazel.StringListAttribute
  347. // Sysprop sources
  348. syspropSrcs bazel.LabelListAttribute
  349. // Yacc sources
  350. yaccSrc *bazel.LabelAttribute
  351. yaccFlags bazel.StringListAttribute
  352. yaccGenLocationHeader bazel.BoolAttribute
  353. yaccGenPositionHeader bazel.BoolAttribute
  354. rsSrcs bazel.LabelListAttribute
  355. hdrs bazel.LabelListAttribute
  356. rtti bazel.BoolAttribute
  357. // Not affected by arch variants
  358. stl *string
  359. cStd *string
  360. cppStd *string
  361. localIncludes bazel.StringListAttribute
  362. absoluteIncludes bazel.StringListAttribute
  363. includes BazelIncludes
  364. protoSrcs bazel.LabelListAttribute
  365. aidlSrcs bazel.LabelListAttribute
  366. rscriptSrcs bazel.LabelListAttribute
  367. stubsSymbolFile *string
  368. stubsVersions bazel.StringListAttribute
  369. features bazel.StringListAttribute
  370. stem bazel.StringAttribute
  371. suffix bazel.StringAttribute
  372. fdoProfile bazel.LabelAttribute
  373. }
  374. type filterOutFn func(string) bool
  375. // filterOutHiddenVisibility removes the flag specifying hidden visibility as
  376. // this flag is converted to a toolchain feature
  377. func filterOutHiddenVisibility(flag string) bool {
  378. return flag == config.VisibilityHiddenFlag
  379. }
  380. func filterOutStdFlag(flag string) bool {
  381. return strings.HasPrefix(flag, "-std=")
  382. }
  383. func filterOutClangUnknownCflags(flag string) bool {
  384. for _, f := range config.ClangUnknownCflags {
  385. if f == flag {
  386. return true
  387. }
  388. }
  389. return false
  390. }
  391. func parseCommandLineFlags(soongFlags []string, filterOut ...filterOutFn) []string {
  392. var result []string
  393. for _, flag := range soongFlags {
  394. skipFlag := false
  395. for _, filter := range filterOut {
  396. if filter != nil && filter(flag) {
  397. skipFlag = true
  398. }
  399. }
  400. if skipFlag {
  401. continue
  402. }
  403. // Soong's cflags can contain spaces, like `-include header.h`. For
  404. // Bazel's copts, split them up to be compatible with the
  405. // no_copts_tokenization feature.
  406. result = append(result, strings.Split(flag, " ")...)
  407. }
  408. return result
  409. }
  410. func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
  411. // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
  412. // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
  413. if srcsList, ok := parseSrcs(ctx, props); ok {
  414. ca.srcs.SetSelectValue(axis, config, srcsList)
  415. }
  416. localIncludeDirs := props.Local_include_dirs
  417. if axis == bazel.NoConfigAxis {
  418. ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
  419. if includeBuildDirectory(props.Include_build_directory) {
  420. localIncludeDirs = append(localIncludeDirs, ".")
  421. }
  422. }
  423. ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
  424. ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
  425. instructionSet := proptools.StringDefault(props.Instruction_set, "")
  426. if instructionSet == "arm" {
  427. ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm"})
  428. } else if instructionSet != "" && instructionSet != "thumb" {
  429. ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
  430. }
  431. // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
  432. // overridden. In Bazel we always allow overriding, via flags; however, this can cause
  433. // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
  434. // cases.
  435. ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutClangUnknownCflags, filterOutHiddenVisibility))
  436. ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
  437. ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, filterOutClangUnknownCflags))
  438. ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, filterOutClangUnknownCflags))
  439. ca.rtti.SetSelectValue(axis, config, props.Rtti)
  440. }
  441. func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
  442. bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  443. if stlProps, ok := props.(*StlProperties); ok {
  444. if stlProps.Stl == nil {
  445. return
  446. }
  447. if ca.stl == nil {
  448. stl := deduplicateStlInput(*stlProps.Stl)
  449. ca.stl = &stl
  450. } else if ca.stl != stlProps.Stl {
  451. ctx.ModuleErrorf("Unsupported conversion: module with different stl for different variants: %s and %s", *ca.stl, stlProps.Stl)
  452. }
  453. }
  454. })
  455. }
  456. func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
  457. productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
  458. "Cflags": &ca.copts,
  459. "Asflags": &ca.asFlags,
  460. "Cppflags": &ca.cppFlags,
  461. }
  462. for propName, attr := range productVarPropNameToAttribute {
  463. if productConfigProps, exists := productVariableProps[propName]; exists {
  464. for productConfigProp, prop := range productConfigProps {
  465. flags, ok := prop.([]string)
  466. if !ok {
  467. ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
  468. }
  469. newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name())
  470. attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
  471. }
  472. }
  473. }
  474. }
  475. func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
  476. ca.srcs.ResolveExcludes()
  477. partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
  478. ca.protoSrcs = partitionedSrcs[protoSrcPartition]
  479. ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
  480. for p, lla := range partitionedSrcs {
  481. // if there are no sources, there is no need for headers
  482. if lla.IsEmpty() {
  483. continue
  484. }
  485. lla.Append(implementationHdrs)
  486. partitionedSrcs[p] = lla
  487. }
  488. ca.srcs = partitionedSrcs[cppSrcPartition]
  489. ca.cSrcs = partitionedSrcs[cSrcPartition]
  490. ca.asSrcs = partitionedSrcs[asSrcPartition]
  491. ca.asmSrcs = partitionedSrcs[asmSrcPartition]
  492. ca.lSrcs = partitionedSrcs[lSrcPartition]
  493. ca.llSrcs = partitionedSrcs[llSrcPartition]
  494. if yacc := partitionedSrcs[yaccSrcPartition]; !yacc.IsEmpty() {
  495. if len(yacc.Value.Includes) > 1 {
  496. ctx.PropertyErrorf("srcs", "Found multiple yacc (.y/.yy) files in library")
  497. }
  498. ca.yaccSrc = bazel.MakeLabelAttribute(yacc.Value.Includes[0].Label)
  499. }
  500. ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
  501. ca.rscriptSrcs = partitionedSrcs[rScriptSrcPartition]
  502. ca.absoluteIncludes.DeduplicateAxesFromBase()
  503. ca.localIncludes.DeduplicateAxesFromBase()
  504. }
  505. // Parse srcs from an arch or OS's props value.
  506. func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
  507. anySrcs := false
  508. // Add srcs-like dependencies such as generated files.
  509. // First create a LabelList containing these dependencies, then merge the values with srcs.
  510. genSrcs, _ := android.PartitionXsdSrcs(ctx, props.Generated_sources)
  511. generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, genSrcs, props.Exclude_generated_sources)
  512. if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
  513. anySrcs = true
  514. }
  515. allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
  516. if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
  517. anySrcs = true
  518. }
  519. return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
  520. }
  521. func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
  522. defaultVal := prefix + "_std_default"
  523. // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
  524. // Defaults are handled by the toolchain definition.
  525. // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
  526. stdVal := proptools.StringDefault(std, defaultVal)
  527. if stdVal == "experimental" || stdVal == defaultVal {
  528. if stdVal == "experimental" {
  529. stdVal = prefix + "_std_experimental"
  530. }
  531. if !useGnu {
  532. stdVal += "_no_gnu"
  533. }
  534. } else if !useGnu {
  535. stdVal = gnuToCReplacer.Replace(stdVal)
  536. }
  537. if stdVal == defaultVal {
  538. return nil
  539. }
  540. return &stdVal
  541. }
  542. func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
  543. useGnu := useGnuExtensions(gnu_extensions)
  544. return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
  545. }
  546. // packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
  547. // is fully-qualified.
  548. // e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
  549. func packageFromLabel(label string) (string, bool) {
  550. split := strings.Split(label, ":")
  551. if len(split) != 2 {
  552. return "", false
  553. }
  554. if split[0] == "" {
  555. return ".", false
  556. }
  557. // remove leading "//"
  558. return split[0][2:], true
  559. }
  560. // includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
  561. func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
  562. for _, hdr := range labelList.Includes {
  563. if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
  564. absolute = append(absolute, pkg)
  565. } else if pkg != "" {
  566. relative = append(relative, pkg)
  567. }
  568. }
  569. return relative, absolute
  570. }
  571. type YasmAttributes struct {
  572. Srcs bazel.LabelListAttribute
  573. Flags bazel.StringListAttribute
  574. Include_dirs bazel.StringListAttribute
  575. }
  576. func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
  577. if ca.asmSrcs.IsEmpty() {
  578. return nil
  579. }
  580. // Yasm needs the include directories from both local_includes and
  581. // export_include_dirs. We don't care about actually exporting them from the
  582. // yasm rule though, because they will also be present on the cc_ rule that
  583. // wraps this yasm rule.
  584. includes := ca.localIncludes.Clone()
  585. bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  586. if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
  587. if len(flagExporterProperties.Export_include_dirs) > 0 {
  588. x := bazel.StringListAttribute{}
  589. x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
  590. includes.Append(x)
  591. }
  592. }
  593. })
  594. ctx.CreateBazelTargetModule(
  595. bazel.BazelTargetModuleProperties{
  596. Rule_class: "yasm",
  597. Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
  598. },
  599. android.CommonAttributes{Name: m.Name() + "_yasm"},
  600. &YasmAttributes{
  601. Srcs: ca.asmSrcs,
  602. Flags: ca.asFlags,
  603. Include_dirs: *includes,
  604. })
  605. // We only want to add a dependency on the _yasm target if there are asm
  606. // sources in the current configuration. If there are unconfigured asm
  607. // sources, always add the dependency. Otherwise, add the dependency only
  608. // on the configuration axes and values that had asm sources.
  609. if len(ca.asmSrcs.Value.Includes) > 0 {
  610. return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
  611. }
  612. ret := &bazel.LabelAttribute{}
  613. for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
  614. for cfg := range ca.asmSrcs.ConfigurableValues[axis] {
  615. ret.SetSelectValue(axis, cfg, bazel.Label{Label: ":" + m.Name() + "_yasm"})
  616. }
  617. }
  618. return ret
  619. }
  620. // Replaces //a/b/my_xsd_config with //a/b/my_xsd_config-cpp
  621. func xsdConfigCppTarget(ctx android.BazelConversionPathContext, mod blueprint.Module) string {
  622. callback := func(xsd android.XsdConfigBp2buildTargets) string {
  623. return xsd.CppBp2buildTargetName()
  624. }
  625. return android.XsdConfigBp2buildTarget(ctx, mod, callback)
  626. }
  627. // bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
  628. func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
  629. archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
  630. archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
  631. archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
  632. var implementationHdrs bazel.LabelListAttribute
  633. axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
  634. allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
  635. for axis, configMap := range cp {
  636. if _, ok := axisToConfigs[axis]; !ok {
  637. axisToConfigs[axis] = map[string]bool{}
  638. }
  639. for cfg := range configMap {
  640. axisToConfigs[axis][cfg] = true
  641. }
  642. }
  643. }
  644. allAxesAndConfigs(archVariantCompilerProps)
  645. allAxesAndConfigs(archVariantLinkerProps)
  646. allAxesAndConfigs(archVariantLibraryProperties)
  647. compilerAttrs := compilerAttributes{}
  648. linkerAttrs := linkerAttributes{}
  649. var aidlLibs bazel.LabelList
  650. // Iterate through these axes in a deterministic order. This is required
  651. // because processing certain dependencies may result in concatenating
  652. // elements along other axes. (For example, processing NoConfig may result
  653. // in elements being added to InApex). This is thus the only way to ensure
  654. // that the order of entries in each list is in a predictable order.
  655. for _, axis := range bazel.SortedConfigurationAxes(axisToConfigs) {
  656. configs := axisToConfigs[axis]
  657. for cfg := range configs {
  658. var allHdrs []string
  659. if baseCompilerProps, ok := archVariantCompilerProps[axis][cfg].(*BaseCompilerProperties); ok {
  660. ah, allHdrsXsd := android.PartitionXsdSrcs(ctx, baseCompilerProps.Generated_headers)
  661. allHdrs = ah
  662. // in the synthetic bp2build workspace, xsd sources are compiled to a static library
  663. xsdCppConfigLibraryLabels := android.BazelLabelForModuleDepsWithFn(ctx, allHdrsXsd, xsdConfigCppTarget)
  664. iwad := linkerAttrs.implementationWholeArchiveDeps.SelectValue(axis, cfg)
  665. (&iwad).Append(xsdCppConfigLibraryLabels)
  666. linkerAttrs.implementationWholeArchiveDeps.SetSelectValue(axis, cfg, bazel.FirstUniqueBazelLabelList(iwad))
  667. if baseCompilerProps.Lex != nil {
  668. compilerAttrs.lexopts.SetSelectValue(axis, cfg, baseCompilerProps.Lex.Flags)
  669. }
  670. if baseCompilerProps.Yacc != nil {
  671. compilerAttrs.yaccFlags.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Flags)
  672. compilerAttrs.yaccGenLocationHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_location_hh)
  673. compilerAttrs.yaccGenPositionHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_position_hh)
  674. }
  675. (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, cfg, baseCompilerProps)
  676. aidlLibs.Append(android.BazelLabelForModuleDeps(ctx, baseCompilerProps.Aidl.Libs))
  677. }
  678. var exportHdrs []string
  679. if baseLinkerProps, ok := archVariantLinkerProps[axis][cfg].(*BaseLinkerProperties); ok {
  680. exportHdrs = baseLinkerProps.Export_generated_headers
  681. (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module, axis, cfg, baseLinkerProps)
  682. }
  683. headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
  684. implementationHdrs.SetSelectValue(axis, cfg, headers.implementation)
  685. compilerAttrs.hdrs.SetSelectValue(axis, cfg, headers.export)
  686. exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
  687. compilerAttrs.includes.Includes.SetSelectValue(axis, cfg, exportIncludes)
  688. compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, cfg, exportAbsoluteIncludes)
  689. includes, absoluteIncludes := includesFromLabelList(headers.implementation)
  690. currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, cfg)
  691. currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
  692. compilerAttrs.absoluteIncludes.SetSelectValue(axis, cfg, currAbsoluteIncludes)
  693. currIncludes := compilerAttrs.localIncludes.SelectValue(axis, cfg)
  694. currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
  695. compilerAttrs.localIncludes.SetSelectValue(axis, cfg, currIncludes)
  696. if libraryProps, ok := archVariantLibraryProperties[axis][cfg].(*LibraryProperties); ok {
  697. if axis == bazel.NoConfigAxis {
  698. if libraryProps.Stubs.Symbol_file != nil {
  699. compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
  700. versions := android.CopyOf(libraryProps.Stubs.Versions)
  701. normalizeVersions(ctx, versions)
  702. versions = addCurrentVersionIfNotPresent(versions)
  703. compilerAttrs.stubsVersions.SetSelectValue(axis, cfg, versions)
  704. }
  705. }
  706. if stem := libraryProps.Stem; stem != nil {
  707. compilerAttrs.stem.SetSelectValue(axis, cfg, stem)
  708. }
  709. if suffix := libraryProps.Suffix; suffix != nil {
  710. compilerAttrs.suffix.SetSelectValue(axis, cfg, suffix)
  711. }
  712. }
  713. }
  714. }
  715. compilerAttrs.convertStlProps(ctx, module)
  716. (&linkerAttrs).convertStripProps(ctx, module)
  717. var nativeCoverage *bool
  718. if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
  719. !Bool(module.coverage.Properties.Native_coverage) {
  720. nativeCoverage = BoolPtr(false)
  721. }
  722. productVariableProps := android.ProductVariableProperties(ctx, ctx.Module())
  723. (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
  724. (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
  725. (&compilerAttrs).finalize(ctx, implementationHdrs)
  726. (&linkerAttrs).finalize(ctx)
  727. (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
  728. protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
  729. // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
  730. // which. This will add the newly generated proto library to the appropriate attribute and nothing
  731. // to the other
  732. (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
  733. (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
  734. aidlDep := bp2buildCcAidlLibrary(
  735. ctx, module,
  736. compilerAttrs.aidlSrcs,
  737. bazel.LabelListAttribute{
  738. Value: aidlLibs,
  739. },
  740. linkerAttrs,
  741. compilerAttrs,
  742. )
  743. if aidlDep != nil {
  744. if lib, ok := module.linker.(*libraryDecorator); ok {
  745. if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
  746. (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
  747. } else {
  748. (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
  749. }
  750. }
  751. }
  752. // Create a cc_yacc_static_library if srcs contains .y/.yy files
  753. // This internal target will produce an .a file that will be statically linked to the parent library
  754. if yaccDep := bp2buildCcYaccLibrary(ctx, compilerAttrs, linkerAttrs); yaccDep != nil {
  755. (&linkerAttrs).implementationWholeArchiveDeps.Add(yaccDep)
  756. }
  757. convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
  758. (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
  759. (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
  760. if module.afdo != nil && module.afdo.Properties.Afdo {
  761. fdoProfileDep := bp2buildFdoProfile(ctx, module)
  762. if fdoProfileDep != nil {
  763. (&compilerAttrs).fdoProfile.SetValue(*fdoProfileDep)
  764. }
  765. }
  766. if !compilerAttrs.syspropSrcs.IsEmpty() {
  767. (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
  768. }
  769. linkerAttrs.wholeArchiveDeps.Prepend = true
  770. linkerAttrs.deps.Prepend = true
  771. compilerAttrs.localIncludes.Prepend = true
  772. compilerAttrs.absoluteIncludes.Prepend = true
  773. compilerAttrs.hdrs.Prepend = true
  774. convertedRsSrcs, rsAbsIncludes, rsLocalIncludes := bp2buildRScript(ctx, module, compilerAttrs)
  775. (&compilerAttrs).srcs.Add(&convertedRsSrcs)
  776. (&compilerAttrs).absoluteIncludes.Append(rsAbsIncludes)
  777. (&compilerAttrs).localIncludes.Append(rsLocalIncludes)
  778. (&compilerAttrs).localIncludes.Value = android.FirstUniqueStrings(compilerAttrs.localIncludes.Value)
  779. features := compilerAttrs.features.Clone().Append(linkerAttrs.features).Append(bp2buildSanitizerFeatures(ctx, module))
  780. features = features.Append(bp2buildLtoFeatures(ctx, module))
  781. features = features.Append(convertHiddenVisibilityToFeatureBase(ctx, module))
  782. features.DeduplicateAxesFromBase()
  783. addMuslSystemDynamicDeps(ctx, linkerAttrs)
  784. return baseAttributes{
  785. compilerAttrs,
  786. linkerAttrs,
  787. *features,
  788. protoDep.protoDep,
  789. aidlDep,
  790. nativeCoverage,
  791. }
  792. }
  793. type ccYaccLibraryAttributes struct {
  794. Src bazel.LabelAttribute
  795. Flags bazel.StringListAttribute
  796. Gen_location_hh bazel.BoolAttribute
  797. Gen_position_hh bazel.BoolAttribute
  798. Local_includes bazel.StringListAttribute
  799. Implementation_deps bazel.LabelListAttribute
  800. Implementation_dynamic_deps bazel.LabelListAttribute
  801. }
  802. func bp2buildCcYaccLibrary(ctx android.Bp2buildMutatorContext, ca compilerAttributes, la linkerAttributes) *bazel.LabelAttribute {
  803. if ca.yaccSrc == nil {
  804. return nil
  805. }
  806. yaccLibraryLabel := ctx.Module().Name() + "_yacc"
  807. ctx.CreateBazelTargetModule(
  808. bazel.BazelTargetModuleProperties{
  809. Rule_class: "cc_yacc_static_library",
  810. Bzl_load_location: "//build/bazel/rules/cc:cc_yacc_library.bzl",
  811. },
  812. android.CommonAttributes{
  813. Name: yaccLibraryLabel,
  814. },
  815. &ccYaccLibraryAttributes{
  816. Src: *ca.yaccSrc,
  817. Flags: ca.yaccFlags,
  818. Gen_location_hh: ca.yaccGenLocationHeader,
  819. Gen_position_hh: ca.yaccGenPositionHeader,
  820. Local_includes: ca.localIncludes,
  821. Implementation_deps: la.implementationDeps,
  822. Implementation_dynamic_deps: la.implementationDynamicDeps,
  823. },
  824. )
  825. yaccLibrary := &bazel.LabelAttribute{
  826. Value: &bazel.Label{
  827. Label: ":" + yaccLibraryLabel,
  828. },
  829. }
  830. return yaccLibrary
  831. }
  832. // As a workaround for b/261657184, we are manually adding the default value
  833. // of system_dynamic_deps for the linux_musl os.
  834. // TODO: Solve this properly
  835. func addMuslSystemDynamicDeps(ctx android.Bp2buildMutatorContext, attrs linkerAttributes) {
  836. systemDynamicDeps := attrs.systemDynamicDeps.SelectValue(bazel.OsConfigurationAxis, "linux_musl")
  837. if attrs.systemDynamicDeps.HasAxisSpecificValues(bazel.OsConfigurationAxis) && systemDynamicDeps.IsNil() {
  838. attrs.systemDynamicDeps.SetSelectValue(bazel.OsConfigurationAxis, "linux_musl", android.BazelLabelForModuleDeps(ctx, config.MuslDefaultSharedLibraries))
  839. }
  840. }
  841. type fdoProfileAttributes struct {
  842. Absolute_path_profile string
  843. }
  844. func bp2buildFdoProfile(
  845. ctx android.Bp2buildMutatorContext,
  846. m *Module,
  847. ) *bazel.Label {
  848. for _, project := range globalAfdoProfileProjects {
  849. // Ensure handcrafted BUILD file exists in the project
  850. BUILDPath := android.ExistentPathForSource(ctx, project, "BUILD")
  851. if BUILDPath.Valid() {
  852. // We handcraft a BUILD file with fdo_profile targets that use the existing profiles in the project
  853. // This implementation is assuming that every afdo profile in globalAfdoProfileProjects already has
  854. // an associated fdo_profile target declared in the same package.
  855. // TODO(b/260714900): Handle arch-specific afdo profiles (e.g. `<module-name>-arm<64>.afdo`)
  856. path := android.ExistentPathForSource(ctx, project, m.Name()+".afdo")
  857. if path.Valid() {
  858. // FIXME: Some profiles only exist internally and are not released to AOSP.
  859. // When generated BUILD files are checked in, we'll run into merge conflict.
  860. // The cc_library_shared target in AOSP won't have reference to an fdo_profile target because
  861. // the profile doesn't exist. Internally, the same cc_library_shared target will
  862. // have reference to the fdo_profile.
  863. // For more context, see b/258682955#comment2
  864. fdoProfileLabel := "//" + strings.TrimSuffix(project, "/") + ":" + m.Name()
  865. return &bazel.Label{
  866. Label: fdoProfileLabel,
  867. }
  868. }
  869. }
  870. }
  871. return nil
  872. }
  873. func bp2buildCcAidlLibrary(
  874. ctx android.Bp2buildMutatorContext,
  875. m *Module,
  876. aidlSrcs bazel.LabelListAttribute,
  877. aidlLibs bazel.LabelListAttribute,
  878. linkerAttrs linkerAttributes,
  879. compilerAttrs compilerAttributes,
  880. ) *bazel.LabelAttribute {
  881. var aidlLibsFromSrcs, aidlFiles bazel.LabelListAttribute
  882. apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), ctx.Module())
  883. if !aidlSrcs.IsEmpty() {
  884. aidlLibsFromSrcs, aidlFiles = aidlSrcs.Partition(func(src bazel.Label) bool {
  885. if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
  886. fg.ShouldConvertToAidlLibrary(ctx) {
  887. return true
  888. }
  889. return false
  890. })
  891. if !aidlFiles.IsEmpty() {
  892. aidlLibName := m.Name() + "_aidl_library"
  893. ctx.CreateBazelTargetModule(
  894. bazel.BazelTargetModuleProperties{
  895. Rule_class: "aidl_library",
  896. Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
  897. },
  898. android.CommonAttributes{
  899. Name: aidlLibName,
  900. Tags: apexAvailableTags,
  901. },
  902. &aidlLibraryAttributes{
  903. Srcs: aidlFiles,
  904. },
  905. )
  906. aidlLibsFromSrcs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
  907. }
  908. }
  909. allAidlLibs := aidlLibs.Clone()
  910. allAidlLibs.Append(aidlLibsFromSrcs)
  911. if !allAidlLibs.IsEmpty() {
  912. ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
  913. // Since parent cc_library already has these dependencies, we can add them as implementation
  914. // deps so that they don't re-export
  915. implementationDeps := linkerAttrs.deps.Clone()
  916. implementationDeps.Append(linkerAttrs.implementationDeps)
  917. implementationDynamicDeps := linkerAttrs.dynamicDeps.Clone()
  918. implementationDynamicDeps.Append(linkerAttrs.implementationDynamicDeps)
  919. sdkAttrs := bp2BuildParseSdkAttributes(m)
  920. exportedIncludes := bp2BuildParseExportedIncludes(ctx, m, &compilerAttrs.includes)
  921. includeAttrs := includesAttributes{
  922. Export_includes: exportedIncludes.Includes,
  923. Export_absolute_includes: exportedIncludes.AbsoluteIncludes,
  924. Export_system_includes: exportedIncludes.SystemIncludes,
  925. Local_includes: compilerAttrs.localIncludes,
  926. Absolute_includes: compilerAttrs.absoluteIncludes,
  927. }
  928. ctx.CreateBazelTargetModule(
  929. bazel.BazelTargetModuleProperties{
  930. Rule_class: "cc_aidl_library",
  931. Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
  932. },
  933. android.CommonAttributes{Name: ccAidlLibrarylabel},
  934. &ccAidlLibraryAttributes{
  935. Deps: *allAidlLibs,
  936. Implementation_deps: *implementationDeps,
  937. Implementation_dynamic_deps: *implementationDynamicDeps,
  938. Tags: apexAvailableTags,
  939. sdkAttributes: sdkAttrs,
  940. includesAttributes: includeAttrs,
  941. },
  942. )
  943. label := &bazel.LabelAttribute{
  944. Value: &bazel.Label{
  945. Label: ":" + ccAidlLibrarylabel,
  946. },
  947. }
  948. return label
  949. }
  950. return nil
  951. }
  952. func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
  953. return sdkAttributes{
  954. Sdk_version: module.Properties.Sdk_version,
  955. Min_sdk_version: module.Properties.Min_sdk_version,
  956. }
  957. }
  958. type sdkAttributes struct {
  959. Sdk_version *string
  960. Min_sdk_version *string
  961. }
  962. // Convenience struct to hold all attributes parsed from linker properties.
  963. type linkerAttributes struct {
  964. deps bazel.LabelListAttribute
  965. implementationDeps bazel.LabelListAttribute
  966. dynamicDeps bazel.LabelListAttribute
  967. implementationDynamicDeps bazel.LabelListAttribute
  968. runtimeDeps bazel.LabelListAttribute
  969. wholeArchiveDeps bazel.LabelListAttribute
  970. implementationWholeArchiveDeps bazel.LabelListAttribute
  971. systemDynamicDeps bazel.LabelListAttribute
  972. usedSystemDynamicDepAsDynamicDep map[string]bool
  973. useVersionLib bazel.BoolAttribute
  974. linkopts bazel.StringListAttribute
  975. additionalLinkerInputs bazel.LabelListAttribute
  976. stripKeepSymbols bazel.BoolAttribute
  977. stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
  978. stripKeepSymbolsList bazel.StringListAttribute
  979. stripAll bazel.BoolAttribute
  980. stripNone bazel.BoolAttribute
  981. features bazel.StringListAttribute
  982. }
  983. var (
  984. soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
  985. versionLib = "libbuildversion"
  986. )
  987. // resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
  988. // since all libs are already excluded by default
  989. func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, props *BaseLinkerProperties) {
  990. excludeSharedLibs := bazelLabelForSharedDeps(ctx, props.Target.Apex.Exclude_shared_libs)
  991. sharedExcludes := bazel.LabelList{Excludes: excludeSharedLibs.Includes}
  992. sharedExcludesLabelList := bazel.LabelListAttribute{}
  993. sharedExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, sharedExcludes)
  994. la.dynamicDeps.Append(sharedExcludesLabelList)
  995. la.implementationDynamicDeps.Append(sharedExcludesLabelList)
  996. excludeStaticLibs := bazelLabelForStaticDeps(ctx, props.Target.Apex.Exclude_static_libs)
  997. staticExcludes := bazel.LabelList{Excludes: excludeStaticLibs.Includes}
  998. staticExcludesLabelList := bazel.LabelListAttribute{}
  999. staticExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, staticExcludes)
  1000. la.deps.Append(staticExcludesLabelList)
  1001. la.implementationDeps.Append(staticExcludesLabelList)
  1002. }
  1003. func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, module *Module, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
  1004. isBinary := module.Binary()
  1005. // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
  1006. var axisFeatures []string
  1007. wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
  1008. staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
  1009. if axis == bazel.NoConfigAxis {
  1010. la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
  1011. if proptools.Bool(props.Use_version_lib) {
  1012. versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
  1013. // remove from static libs so there is no duplicate dependency
  1014. _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
  1015. // only add the dep if it is not in progress
  1016. if !versionLibAlreadyInDeps {
  1017. wholeStaticLibs = append(wholeStaticLibs, versionLib)
  1018. }
  1019. }
  1020. }
  1021. // Excludes to parallel Soong:
  1022. // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
  1023. la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
  1024. staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
  1025. ctx,
  1026. !isBinary,
  1027. staticLibs,
  1028. props.Exclude_static_libs,
  1029. props.Export_static_lib_headers,
  1030. bazelLabelForStaticDepsExcludes,
  1031. )
  1032. headerLibs := android.FirstUniqueStrings(props.Header_libs)
  1033. hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
  1034. (&hDeps.export).Append(staticDeps.export)
  1035. la.deps.SetSelectValue(axis, config, hDeps.export)
  1036. (&hDeps.implementation).Append(staticDeps.implementation)
  1037. la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
  1038. systemSharedLibs := props.System_shared_libs
  1039. // systemSharedLibs distinguishes between nil/empty list behavior:
  1040. // nil -> use default values
  1041. // empty list -> no values specified
  1042. if len(systemSharedLibs) > 0 {
  1043. systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
  1044. }
  1045. la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
  1046. sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
  1047. excludeSharedLibs := props.Exclude_shared_libs
  1048. usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
  1049. return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
  1050. })
  1051. for _, el := range usedSystem {
  1052. if la.usedSystemDynamicDepAsDynamicDep == nil {
  1053. la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
  1054. }
  1055. la.usedSystemDynamicDepAsDynamicDep[el] = true
  1056. }
  1057. sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
  1058. ctx,
  1059. !isBinary,
  1060. sharedLibs,
  1061. props.Exclude_shared_libs,
  1062. props.Export_shared_lib_headers,
  1063. bazelLabelForSharedDepsExcludes,
  1064. )
  1065. la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
  1066. la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
  1067. la.resolveTargetApexProp(ctx, props)
  1068. if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
  1069. // If a dependency in la.implementationDynamicDeps or la.dynamicDeps has stubs, its
  1070. // stub variant should be used when the dependency is linked in a APEX. The
  1071. // dependencies in NoConfigAxis and OsConfigurationAxis/OsAndroid are grouped by
  1072. // having stubs or not, so Bazel select() statement can be used to choose
  1073. // source/stub variants of them.
  1074. apexAvailable := module.ApexAvailable()
  1075. setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.export, &la.dynamicDeps, 0, false)
  1076. setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.implementation, &la.implementationDynamicDeps, 1, false)
  1077. if len(systemSharedLibs) > 0 {
  1078. setStubsForDynamicDeps(ctx, axis, config, apexAvailable, bazelLabelForSharedDeps(ctx, systemSharedLibs), &la.systemDynamicDeps, 2, true)
  1079. }
  1080. }
  1081. if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
  1082. axisFeatures = append(axisFeatures, "disable_pack_relocations")
  1083. }
  1084. if Bool(props.Allow_undefined_symbols) {
  1085. axisFeatures = append(axisFeatures, "-no_undefined_symbols")
  1086. }
  1087. var linkerFlags []string
  1088. if len(props.Ldflags) > 0 {
  1089. linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
  1090. // binaries remove static flag if -shared is in the linker flags
  1091. if isBinary && android.InList("-shared", linkerFlags) {
  1092. axisFeatures = append(axisFeatures, "-static_flag")
  1093. }
  1094. }
  1095. if !props.libCrt() {
  1096. axisFeatures = append(axisFeatures, "-use_libcrt")
  1097. }
  1098. if !props.crt() {
  1099. axisFeatures = append(axisFeatures, "-link_crt")
  1100. }
  1101. // This must happen before the addition of flags for Version Script and
  1102. // Dynamic List, as these flags must be split on spaces and those must not
  1103. linkerFlags = parseCommandLineFlags(linkerFlags, filterOutClangUnknownCflags)
  1104. additionalLinkerInputs := bazel.LabelList{}
  1105. if props.Version_script != nil {
  1106. label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
  1107. additionalLinkerInputs.Add(&label)
  1108. linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
  1109. axisFeatures = append(axisFeatures, "android_cfi_exports_map")
  1110. }
  1111. if props.Dynamic_list != nil {
  1112. label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
  1113. additionalLinkerInputs.Add(&label)
  1114. linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
  1115. }
  1116. la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
  1117. if axis == bazel.OsConfigurationAxis && (config == bazel.OsDarwin || config == bazel.OsLinux || config == bazel.OsWindows) {
  1118. linkerFlags = append(linkerFlags, props.Host_ldlibs...)
  1119. }
  1120. la.linkopts.SetSelectValue(axis, config, linkerFlags)
  1121. if axisFeatures != nil {
  1122. la.features.SetSelectValue(axis, config, axisFeatures)
  1123. }
  1124. runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
  1125. if !runtimeDeps.IsEmpty() {
  1126. la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
  1127. }
  1128. }
  1129. var (
  1130. apiSurfaceModuleLibCurrentPackage = "@api_surfaces//" + android.ModuleLibApi.String() + "/current:"
  1131. )
  1132. func availableToSameApexes(a, b []string) bool {
  1133. if len(a) == 0 && len(b) == 0 {
  1134. return true
  1135. }
  1136. differ, _, _ := android.ListSetDifference(a, b)
  1137. return !differ
  1138. }
  1139. var (
  1140. apiDomainConfigSettingKey = android.NewOnceKey("apiDomainConfigSettingKey")
  1141. apiDomainConfigSettingLock sync.Mutex
  1142. )
  1143. func getApiDomainConfigSettingMap(config android.Config) *map[string]bool {
  1144. return config.Once(apiDomainConfigSettingKey, func() interface{} {
  1145. return &map[string]bool{}
  1146. }).(*map[string]bool)
  1147. }
  1148. var (
  1149. testApexNameToApiDomain = map[string]string{
  1150. "test_broken_com.android.art": "com.android.art",
  1151. }
  1152. )
  1153. // GetApiDomain returns the canonical name of the apex. This is synonymous to the apex_name definition.
  1154. // https://cs.android.com/android/_/android/platform/build/soong/+/e3f0281b8897da1fe23b2f4f3a05f1dc87bcc902:apex/prebuilt.go;l=81-83;drc=2dc7244af985a6ad701b22f1271e606cabba527f;bpv=1;bpt=0
  1155. // For test apexes, it uses a naming convention heuristic to determine the api domain.
  1156. // TODO (b/281548611): Move this build/soong/android
  1157. func GetApiDomain(apexName string) string {
  1158. if apiDomain, exists := testApexNameToApiDomain[apexName]; exists {
  1159. return apiDomain
  1160. }
  1161. // Remove `test_` prefix
  1162. return strings.TrimPrefix(apexName, "test_")
  1163. }
  1164. // Create a config setting for this apex in build/bazel/rules/apex
  1165. // The use case for this is stub/impl selection in cc libraries
  1166. // Long term, these config_setting(s) should be colocated with the respective apex definitions.
  1167. // Note that this is an anti-pattern: The config_setting should be created from the apex definition
  1168. // and not from a cc_library.
  1169. // This anti-pattern is needed today since not all apexes have been allowlisted.
  1170. func createInApexConfigSetting(ctx android.TopDownMutatorContext, apexName string) {
  1171. if apexName == android.AvailableToPlatform || apexName == android.AvailableToAnyApex {
  1172. // These correspond to android-non_apex and android-in_apex
  1173. return
  1174. }
  1175. apiDomainConfigSettingLock.Lock()
  1176. defer apiDomainConfigSettingLock.Unlock()
  1177. // Return if a config_setting has already been created
  1178. apiDomain := GetApiDomain(apexName)
  1179. acsm := getApiDomainConfigSettingMap(ctx.Config())
  1180. if _, exists := (*acsm)[apiDomain]; exists {
  1181. return
  1182. }
  1183. (*acsm)[apiDomain] = true
  1184. csa := bazel.ConfigSettingAttributes{
  1185. Flag_values: bazel.StringMapAttribute{
  1186. "//build/bazel/rules/apex:api_domain": apiDomain,
  1187. },
  1188. // Constraint this to android
  1189. Constraint_values: bazel.MakeLabelListAttribute(
  1190. bazel.MakeLabelList(
  1191. []bazel.Label{
  1192. bazel.Label{Label: "//build/bazel/platforms/os:android"},
  1193. },
  1194. ),
  1195. ),
  1196. }
  1197. ca := android.CommonAttributes{
  1198. Name: apiDomain,
  1199. }
  1200. ctx.CreateBazelConfigSetting(
  1201. csa,
  1202. ca,
  1203. "build/bazel/rules/apex",
  1204. )
  1205. }
  1206. func inApexConfigSetting(apexAvailable string) string {
  1207. if apexAvailable == android.AvailableToPlatform {
  1208. return bazel.AndroidPlatform
  1209. }
  1210. if apexAvailable == android.AvailableToAnyApex {
  1211. return bazel.AndroidAndInApex
  1212. }
  1213. apiDomain := GetApiDomain(apexAvailable)
  1214. return "//build/bazel/rules/apex:" + apiDomain
  1215. }
  1216. // Inputs to stub vs impl selection.
  1217. type stubSelectionInfo struct {
  1218. // Label of the implementation library (e.g. //bionic/libc:libc)
  1219. impl bazel.Label
  1220. // Axis containing the implementation library
  1221. axis bazel.ConfigurationAxis
  1222. // Axis key containing the implementation library
  1223. config string
  1224. // API domain of the apex
  1225. // For test apexes (test_com.android.foo), this will be the source apex (com.android.foo)
  1226. apiDomain string
  1227. // List of dep labels
  1228. dynamicDeps *bazel.LabelListAttribute
  1229. // Boolean value for determining if the dep is in the same api domain
  1230. // If false, the label will be rewritten to to the stub label
  1231. sameApiDomain bool
  1232. }
  1233. func useStubOrImplInApexWithName(ssi stubSelectionInfo) {
  1234. lib := ssi.impl
  1235. if !ssi.sameApiDomain {
  1236. lib = bazel.Label{
  1237. Label: apiSurfaceModuleLibCurrentPackage + strings.TrimPrefix(lib.OriginalModuleName, ":"),
  1238. }
  1239. }
  1240. // Create a select statement specific to this apex
  1241. inApexSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain))
  1242. (&inApexSelectValue).Append(bazel.MakeLabelList([]bazel.Label{lib}))
  1243. ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain), bazel.FirstUniqueBazelLabelList(inApexSelectValue))
  1244. // Delete the library from the common config for this apex
  1245. implDynamicDeps := ssi.dynamicDeps.SelectValue(ssi.axis, ssi.config)
  1246. implDynamicDeps = bazel.SubtractBazelLabelList(implDynamicDeps, bazel.MakeLabelList([]bazel.Label{ssi.impl}))
  1247. ssi.dynamicDeps.SetSelectValue(ssi.axis, ssi.config, implDynamicDeps)
  1248. if ssi.axis == bazel.NoConfigAxis {
  1249. // Set defaults. Defaults (i.e. host) should use impl and not stubs.
  1250. defaultSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
  1251. (&defaultSelectValue).Append(bazel.MakeLabelList([]bazel.Label{ssi.impl}))
  1252. ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
  1253. }
  1254. }
  1255. func setStubsForDynamicDeps(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis,
  1256. config string, apexAvailable []string, dynamicLibs bazel.LabelList, dynamicDeps *bazel.LabelListAttribute, ind int, buildNonApexWithStubs bool) {
  1257. // Create a config_setting for each apex_available.
  1258. // This will be used to select impl of a dep if dep is available to the same apex.
  1259. for _, aa := range apexAvailable {
  1260. createInApexConfigSetting(ctx.(android.TopDownMutatorContext), aa)
  1261. }
  1262. apiDomainForSelects := []string{}
  1263. for _, apex := range apexAvailable {
  1264. apiDomainForSelects = append(apiDomainForSelects, GetApiDomain(apex))
  1265. }
  1266. // Always emit a select statement for the platform variant.
  1267. // This ensures that b build //foo --config=android works
  1268. // Soong always creates a platform variant even when the library might not be available to platform.
  1269. if !android.InList(android.AvailableToPlatform, apiDomainForSelects) {
  1270. apiDomainForSelects = append(apiDomainForSelects, android.AvailableToPlatform)
  1271. }
  1272. apiDomainForSelects = android.SortedUniqueStrings(apiDomainForSelects)
  1273. // Create a select for each apex this library could be included in.
  1274. for _, l := range dynamicLibs.Includes {
  1275. dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
  1276. if c, ok := dep.(*Module); !ok || !c.HasStubsVariants() {
  1277. continue
  1278. }
  1279. // TODO (b/280339069): Decrease the verbosity of the generated BUILD files
  1280. for _, apiDomain := range apiDomainForSelects {
  1281. var sameApiDomain bool
  1282. if apiDomain == android.AvailableToPlatform {
  1283. // Platform variants in Soong use equality of apex_available for stub/impl selection.
  1284. // https://cs.android.com/android/_/android/platform/build/soong/+/316b0158fe57ee7764235923e7c6f3d530da39c6:cc/cc.go;l=3393-3404;drc=176271a426496fa2688efe2b40d5c74340c63375;bpv=1;bpt=0
  1285. // One of the factors behind this design choice is cc_test
  1286. // Tests only have a platform variant, and using equality of apex_available ensures
  1287. // that tests of an apex library gets its implementation and not stubs.
  1288. // TODO (b/280343104): Discuss if we can drop this special handling for platform variants.
  1289. sameApiDomain = availableToSameApexes(apexAvailable, dep.(*Module).ApexAvailable())
  1290. if linkable, ok := ctx.Module().(LinkableInterface); ok && linkable.Bootstrap() {
  1291. sameApiDomain = true
  1292. }
  1293. } else {
  1294. sameApiDomain = android.InList(apiDomain, dep.(*Module).ApexAvailable())
  1295. }
  1296. ssi := stubSelectionInfo{
  1297. impl: l,
  1298. axis: axis,
  1299. config: config,
  1300. apiDomain: apiDomain,
  1301. dynamicDeps: dynamicDeps,
  1302. sameApiDomain: sameApiDomain,
  1303. }
  1304. useStubOrImplInApexWithName(ssi)
  1305. }
  1306. }
  1307. }
  1308. func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
  1309. bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  1310. if stripProperties, ok := props.(*StripProperties); ok {
  1311. la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
  1312. la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
  1313. la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
  1314. la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
  1315. la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
  1316. }
  1317. })
  1318. }
  1319. func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
  1320. type productVarDep struct {
  1321. // the name of the corresponding excludes field, if one exists
  1322. excludesField string
  1323. // reference to the bazel attribute that should be set for the given product variable config
  1324. attribute *bazel.LabelListAttribute
  1325. depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
  1326. }
  1327. // an intermediate attribute that holds Header_libs info, and will be appended to
  1328. // implementationDeps at the end, to solve the confliction that both header_libs
  1329. // and static_libs use implementationDeps.
  1330. var headerDeps bazel.LabelListAttribute
  1331. productVarToDepFields := map[string]productVarDep{
  1332. // product variables do not support exclude_shared_libs
  1333. "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
  1334. "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
  1335. "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
  1336. "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
  1337. }
  1338. for name, dep := range productVarToDepFields {
  1339. props, exists := productVariableProps[name]
  1340. excludeProps, excludesExists := productVariableProps[dep.excludesField]
  1341. // if neither an include nor excludes property exists, then skip it
  1342. if !exists && !excludesExists {
  1343. continue
  1344. }
  1345. // Collect all the configurations that an include or exclude property exists for.
  1346. // We want to iterate all configurations rather than either the include or exclude because, for a
  1347. // particular configuration, we may have either only an include or an exclude to handle.
  1348. productConfigProps := make(map[android.ProductConfigOrSoongConfigProperty]bool, len(props)+len(excludeProps))
  1349. for p := range props {
  1350. productConfigProps[p] = true
  1351. }
  1352. for p := range excludeProps {
  1353. productConfigProps[p] = true
  1354. }
  1355. for productConfigProp := range productConfigProps {
  1356. prop, includesExists := props[productConfigProp]
  1357. excludesProp, excludesExists := excludeProps[productConfigProp]
  1358. var includes, excludes []string
  1359. var ok bool
  1360. // if there was no includes/excludes property, casting fails and that's expected
  1361. if includes, ok = prop.([]string); includesExists && !ok {
  1362. ctx.ModuleErrorf("Could not convert product variable %s property", name)
  1363. }
  1364. if excludes, ok = excludesProp.([]string); excludesExists && !ok {
  1365. ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
  1366. }
  1367. dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
  1368. dep.attribute.SetSelectValue(
  1369. productConfigProp.ConfigurationAxis(),
  1370. productConfigProp.SelectKey(),
  1371. dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
  1372. )
  1373. }
  1374. }
  1375. la.implementationDeps.Append(headerDeps)
  1376. }
  1377. func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
  1378. // if system dynamic deps have the default value, any use of a system dynamic library used will
  1379. // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
  1380. // from bionic OSes and the no config case as these libraries only build for bionic OSes.
  1381. if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
  1382. toRemove := bazelLabelForSharedDeps(ctx, android.SortedKeys(la.usedSystemDynamicDepAsDynamicDep))
  1383. la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
  1384. la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
  1385. la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
  1386. la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
  1387. la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
  1388. la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
  1389. la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
  1390. stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
  1391. for _, lib := range toRemove.Includes {
  1392. stubLabelInApiSurfaces := bazel.Label{
  1393. Label: apiSurfaceModuleLibCurrentPackage + lib.OriginalModuleName,
  1394. }
  1395. stubsToRemove = append(stubsToRemove, stubLabelInApiSurfaces)
  1396. }
  1397. // system libraries (e.g. libc, libm, libdl) belong the com.android.runtime api domain
  1398. // dedupe the stubs of these libraries from the other api domains (platform, other_apexes...)
  1399. for _, aa := range ctx.Module().(*Module).ApexAvailable() {
  1400. la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, inApexConfigSetting(aa), bazel.MakeLabelList(stubsToRemove))
  1401. }
  1402. la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidPlatform, bazel.MakeLabelList(stubsToRemove))
  1403. }
  1404. la.deps.ResolveExcludes()
  1405. la.implementationDeps.ResolveExcludes()
  1406. la.dynamicDeps.ResolveExcludes()
  1407. la.implementationDynamicDeps.ResolveExcludes()
  1408. la.wholeArchiveDeps.ResolveExcludes()
  1409. la.systemDynamicDeps.ForceSpecifyEmptyList = true
  1410. }
  1411. // Relativize a list of root-relative paths with respect to the module's
  1412. // directory.
  1413. //
  1414. // include_dirs Soong prop are root-relative (b/183742505), but
  1415. // local_include_dirs, export_include_dirs and export_system_include_dirs are
  1416. // module dir relative. This function makes a list of paths entirely module dir
  1417. // relative.
  1418. //
  1419. // For the `include` attribute, Bazel wants the paths to be relative to the
  1420. // module.
  1421. func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
  1422. var relativePaths []string
  1423. for _, path := range paths {
  1424. // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
  1425. relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
  1426. if err != nil {
  1427. panic(err)
  1428. }
  1429. relativePaths = append(relativePaths, relativePath)
  1430. }
  1431. return relativePaths
  1432. }
  1433. // BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
  1434. // attributes.
  1435. type BazelIncludes struct {
  1436. AbsoluteIncludes bazel.StringListAttribute
  1437. Includes bazel.StringListAttribute
  1438. SystemIncludes bazel.StringListAttribute
  1439. }
  1440. func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
  1441. var exported BazelIncludes
  1442. if includes != nil {
  1443. exported = *includes
  1444. } else {
  1445. exported = BazelIncludes{}
  1446. }
  1447. // cc library Export_include_dirs and Export_system_include_dirs are marked
  1448. // "variant_prepend" in struct tag, set their prepend property to true to make
  1449. // sure bp2build generates correct result.
  1450. exported.Includes.Prepend = true
  1451. exported.SystemIncludes.Prepend = true
  1452. bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  1453. if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
  1454. if len(flagExporterProperties.Export_include_dirs) > 0 {
  1455. exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
  1456. }
  1457. if len(flagExporterProperties.Export_system_include_dirs) > 0 {
  1458. exported.SystemIncludes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.SystemIncludes.SelectValue(axis, config), flagExporterProperties.Export_system_include_dirs...)))
  1459. }
  1460. }
  1461. })
  1462. exported.AbsoluteIncludes.DeduplicateAxesFromBase()
  1463. exported.Includes.DeduplicateAxesFromBase()
  1464. exported.SystemIncludes.DeduplicateAxesFromBase()
  1465. return exported
  1466. }
  1467. func BazelLabelNameForStaticModule(baseLabel string) string {
  1468. return baseLabel + "_bp2build_cc_library_static"
  1469. }
  1470. func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
  1471. label := android.BazelModuleLabel(ctx, m)
  1472. if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary {
  1473. return BazelLabelNameForStaticModule(label)
  1474. }
  1475. return label
  1476. }
  1477. func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
  1478. // cc_library, at it's root name, propagates the shared library, which depends on the static
  1479. // library.
  1480. return android.BazelModuleLabel(ctx, m)
  1481. }
  1482. func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
  1483. label := bazelLabelForStaticModule(ctx, m)
  1484. if aModule, ok := m.(android.Module); ok {
  1485. if android.IsModulePrebuilt(aModule) {
  1486. label += "_alwayslink"
  1487. }
  1488. }
  1489. return label
  1490. }
  1491. func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
  1492. return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
  1493. }
  1494. func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
  1495. return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
  1496. }
  1497. func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
  1498. return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
  1499. }
  1500. func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
  1501. return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
  1502. }
  1503. func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
  1504. return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
  1505. }
  1506. func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
  1507. // This is not elegant, but bp2build's shared library targets only propagate
  1508. // their header information as part of the normal C++ provider.
  1509. return bazelLabelForSharedDeps(ctx, modules)
  1510. }
  1511. func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
  1512. // This is only used when product_variable header_libs is processed, to follow
  1513. // the pattern of depResolutionFunc
  1514. return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
  1515. }
  1516. func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
  1517. return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
  1518. }
  1519. type binaryLinkerAttrs struct {
  1520. Linkshared *bool
  1521. Stem bazel.StringAttribute
  1522. Suffix bazel.StringAttribute
  1523. }
  1524. func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
  1525. attrs := binaryLinkerAttrs{}
  1526. bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  1527. linkerProps := props.(*BinaryLinkerProperties)
  1528. staticExecutable := linkerProps.Static_executable
  1529. if axis == bazel.NoConfigAxis {
  1530. if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
  1531. attrs.Linkshared = &linkBinaryShared
  1532. }
  1533. } else if staticExecutable != nil {
  1534. // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
  1535. // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
  1536. ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
  1537. }
  1538. if stem := linkerProps.Stem; stem != nil {
  1539. attrs.Stem.SetSelectValue(axis, config, stem)
  1540. }
  1541. if suffix := linkerProps.Suffix; suffix != nil {
  1542. attrs.Suffix.SetSelectValue(axis, config, suffix)
  1543. }
  1544. })
  1545. return attrs
  1546. }
  1547. func bp2buildSanitizerFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
  1548. sanitizerFeatures := bazel.StringListAttribute{}
  1549. bp2BuildPropParseHelper(ctx, m, &SanitizeProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  1550. var features []string
  1551. if sanitizerProps, ok := props.(*SanitizeProperties); ok {
  1552. if sanitizerProps.Sanitize.Integer_overflow != nil && *sanitizerProps.Sanitize.Integer_overflow {
  1553. features = append(features, "ubsan_integer_overflow")
  1554. }
  1555. for _, sanitizer := range sanitizerProps.Sanitize.Misc_undefined {
  1556. features = append(features, "ubsan_"+sanitizer)
  1557. }
  1558. blocklist := sanitizerProps.Sanitize.Blocklist
  1559. if blocklist != nil {
  1560. // Format the blocklist name to be used in a feature name
  1561. blocklistFeatureSuffix := strings.Replace(strings.ToLower(*blocklist), ".", "_", -1)
  1562. features = append(features, "ubsan_blocklist_"+blocklistFeatureSuffix)
  1563. }
  1564. if sanitizerProps.Sanitize.Cfi != nil && !proptools.Bool(sanitizerProps.Sanitize.Cfi) {
  1565. features = append(features, "-android_cfi")
  1566. } else if proptools.Bool(sanitizerProps.Sanitize.Cfi) {
  1567. features = append(features, "android_cfi")
  1568. if proptools.Bool(sanitizerProps.Sanitize.Config.Cfi_assembly_support) {
  1569. features = append(features, "android_cfi_assembly_support")
  1570. }
  1571. }
  1572. sanitizerFeatures.SetSelectValue(axis, config, features)
  1573. }
  1574. })
  1575. return sanitizerFeatures
  1576. }
  1577. func bp2buildLtoFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
  1578. lto_feature_name := "android_thin_lto"
  1579. ltoBoolFeatures := bazel.BoolAttribute{}
  1580. bp2BuildPropParseHelper(ctx, m, &LTOProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
  1581. if ltoProps, ok := props.(*LTOProperties); ok {
  1582. thinProp := ltoProps.Lto.Thin != nil && *ltoProps.Lto.Thin
  1583. thinPropSetToFalse := ltoProps.Lto.Thin != nil && !*ltoProps.Lto.Thin
  1584. neverProp := ltoProps.Lto.Never != nil && *ltoProps.Lto.Never
  1585. if thinProp {
  1586. ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(true))
  1587. return
  1588. }
  1589. if neverProp || thinPropSetToFalse {
  1590. if thinProp {
  1591. ctx.ModuleErrorf("lto.thin and lto.never are mutually exclusive but were specified together")
  1592. } else {
  1593. ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(false))
  1594. }
  1595. return
  1596. }
  1597. }
  1598. ltoBoolFeatures.SetSelectValue(axis, config, nil)
  1599. })
  1600. props := m.GetArchVariantProperties(ctx, &LTOProperties{})
  1601. ltoStringFeatures, err := ltoBoolFeatures.ToStringListAttribute(func(boolPtr *bool, axis bazel.ConfigurationAxis, config string) []string {
  1602. if boolPtr == nil {
  1603. return []string{}
  1604. }
  1605. if !*boolPtr {
  1606. return []string{"-" + lto_feature_name}
  1607. }
  1608. features := []string{lto_feature_name}
  1609. if ltoProps, ok := props[axis][config].(*LTOProperties); ok {
  1610. if ltoProps.Whole_program_vtables != nil && *ltoProps.Whole_program_vtables {
  1611. features = append(features, "android_thin_lto_whole_program_vtables")
  1612. }
  1613. }
  1614. return features
  1615. })
  1616. if err != nil {
  1617. ctx.ModuleErrorf("Error processing LTO attributes: %s", err)
  1618. }
  1619. return ltoStringFeatures
  1620. }
  1621. func convertHiddenVisibilityToFeatureBase(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
  1622. visibilityHiddenFeature := bazel.StringListAttribute{}
  1623. bp2BuildPropParseHelper(ctx, m, &BaseCompilerProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
  1624. if baseCompilerProps, ok := props.(*BaseCompilerProperties); ok {
  1625. convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, baseCompilerProps.Cflags)
  1626. }
  1627. })
  1628. return visibilityHiddenFeature
  1629. }
  1630. func convertHiddenVisibilityToFeatureStaticOrShared(ctx android.BazelConversionPathContext, m *Module, isStatic bool) bazel.StringListAttribute {
  1631. visibilityHiddenFeature := bazel.StringListAttribute{}
  1632. if isStatic {
  1633. bp2BuildPropParseHelper(ctx, m, &StaticProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
  1634. if staticProps, ok := props.(*StaticProperties); ok {
  1635. convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, staticProps.Static.Cflags)
  1636. }
  1637. })
  1638. } else {
  1639. bp2BuildPropParseHelper(ctx, m, &SharedProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
  1640. if sharedProps, ok := props.(*SharedProperties); ok {
  1641. convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, sharedProps.Shared.Cflags)
  1642. }
  1643. })
  1644. }
  1645. return visibilityHiddenFeature
  1646. }
  1647. func convertHiddenVisibilityToFeatureHelper(feature *bazel.StringListAttribute, axis bazel.ConfigurationAxis, configString string, cflags []string) {
  1648. if inList(config.VisibilityHiddenFlag, cflags) {
  1649. feature.SetSelectValue(axis, configString, []string{"visibility_hidden"})
  1650. }
  1651. }