bp2build.go 66 KB

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