bp2build.go 58 KB

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