blob: c1a3bef2a9e73feb6905fc346c812eddd3fae726 [file] [log] [blame]
Jingwen Chen91220d72021-03-24 02:18:33 -04001// 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//
Cole Faust7071a052022-07-29 15:58:33 -07007// http://www.apache.org/licenses/LICENSE-2.0
Jingwen Chen91220d72021-03-24 02:18:33 -04008//
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.
14package cc
15
16import (
Liz Kammerd2871182021-10-04 13:54:37 -040017 "fmt"
Jingwen Chened9c17d2021-04-13 07:14:55 +000018 "path/filepath"
Jingwen Chen3950cd62021-05-12 04:33:00 +000019 "strings"
Chris Parsons484e50a2021-05-13 15:13:04 -040020
21 "android/soong/android"
22 "android/soong/bazel"
Alix1be00d42022-05-16 22:56:04 +000023 "android/soong/cc/config"
Liz Kammer7a210ac2021-09-22 15:52:58 -040024
Chris Parsons953b3562021-09-20 15:14:39 -040025 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040026
27 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040028)
29
Liz Kammerae3994e2021-10-19 09:45:48 -040030const (
Liz Kammer12615db2021-09-28 09:19:17 -040031 cSrcPartition = "c"
32 asSrcPartition = "as"
Cole Faust7071a052022-07-29 15:58:33 -070033 asmSrcPartition = "asm"
Trevor Radcliffeef9c9002022-05-13 20:55:35 +000034 lSrcPartition = "l"
35 llSrcPartition = "ll"
Liz Kammer12615db2021-09-28 09:19:17 -040036 cppSrcPartition = "cpp"
37 protoSrcPartition = "proto"
Vinh Tran9f6796a2022-08-16 13:10:31 -040038 aidlSrcPartition = "aidl"
Liz Kammerae3994e2021-10-19 09:45:48 -040039)
40
Liz Kammer2222c6b2021-05-24 15:41:47 -040041// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000042// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040043type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040044 Srcs bazel.LabelListAttribute
45 Srcs_c bazel.LabelListAttribute
46 Srcs_as bazel.LabelListAttribute
47 Srcs_aidl bazel.LabelListAttribute
48 Hdrs bazel.LabelListAttribute
49 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000050
Liz Kammer12615db2021-09-28 09:19:17 -040051 Deps bazel.LabelListAttribute
52 Implementation_deps bazel.LabelListAttribute
53 Dynamic_deps bazel.LabelListAttribute
54 Implementation_dynamic_deps bazel.LabelListAttribute
55 Whole_archive_deps bazel.LabelListAttribute
56 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070057 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040058
59 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050060
61 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080062
Yu Liu8d82ac52022-05-17 15:13:28 -070063 Native_coverage bazel.BoolAttribute
64
Yu Liufc603162022-03-01 15:44:08 -080065 sdkAttributes
Jingwen Chen53681ef2021-04-29 08:15:13 +000066}
67
Sam Delmericoc7681022022-02-04 21:01:20 +000068// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +000069func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -040070 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
71 // macro.
72 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -040073 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
74
75 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -040076 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -040077 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
78 return labelStr, false
79 }
80 // If the filegroup is already converted to aidl_library, skip creating
81 // _c_srcs, _as_srcs, _cpp_srcs filegroups
82 fg, _ := m.(android.Bp2buildAidlLibrary)
83 if fg.ShouldConvertToAidlLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -040084 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000085 }
Liz Kammer12615db2021-09-28 09:19:17 -040086 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040087 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000088 }
89
Liz Kammer57e2e7a2021-09-20 12:55:02 -040090 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +000091 labels := bazel.LabelPartitions{
92 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -050093 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
94 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -070095 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -040096 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +000097 // TODO(http://b/231968910): If there is ever a filegroup target that
98 // contains .l or .ll files we will need to find a way to add a
99 // LabelMapper for these that identifies these filegroups and
100 // converts them appropriately
101 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
102 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400103 // C++ is the "catch-all" group, and comprises generated sources because we don't
104 // know the language of these sources until the genrule is executed.
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500105 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
Sam Delmericoc7681022022-02-04 21:01:20 +0000106 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000107
Sam Delmericoc7681022022-02-04 21:01:20 +0000108 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000109}
110
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000111// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000112func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000113 lib, ok := module.compiler.(*libraryDecorator)
114 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400115 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000116 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000117 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
118}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000119
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000120// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000121func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000122 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000123}
124
125// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000126func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000127 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400128}
129
Liz Kammer7a210ac2021-09-22 15:52:58 -0400130type depsPartition struct {
131 export bazel.LabelList
132 implementation bazel.LabelList
133}
134
Jingwen Chen55bc8202021-11-02 06:40:51 +0000135type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400136
Jingwen Chen55bc8202021-11-02 06:40:51 +0000137func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400138 if !exportsDeps {
139 return depsPartition{
140 implementation: fn(ctx, allDeps),
141 }
142 }
143
Liz Kammer7a210ac2021-09-22 15:52:58 -0400144 implementation, export := android.FilterList(allDeps, exportedDeps)
145
146 return depsPartition{
147 export: fn(ctx, export),
148 implementation: fn(ctx, implementation),
149 }
150}
151
Jingwen Chen55bc8202021-11-02 06:40:51 +0000152type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400153
Jingwen Chen55bc8202021-11-02 06:40:51 +0000154func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400155 if !exportsDeps {
156 return depsPartition{
157 implementation: fn(ctx, allDeps, excludes),
158 }
159 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400160 implementation, export := android.FilterList(allDeps, exportedDeps)
161
162 return depsPartition{
163 export: fn(ctx, export, excludes),
164 implementation: fn(ctx, implementation, excludes),
165 }
166}
167
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000168// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000169func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400170 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000171
Liz Kammer9abd62d2021-05-21 08:37:59 -0400172 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Alix1be00d42022-05-16 22:56:04 +0000173 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, true, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000174 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400175 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400176
Liz Kammer2b8004b2021-10-04 13:55:44 -0400177 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400178 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
179 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
180
Liz Kammer2b8004b2021-10-04 13:55:44 -0400181 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400182 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
183 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
184
185 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500186 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000187 }
Liz Kammer135bf552021-08-11 10:46:06 -0400188 // system_dynamic_deps distinguishes between nil/empty list behavior:
189 // nil -> use default values
190 // empty list -> no values specified
191 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000192
193 if isStatic {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000194 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
195 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
196 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000197 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000198 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000199 } else {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000200 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
201 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
202 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000203 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000204 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000205 }
206
Liz Kammerae3994e2021-10-19 09:45:48 -0400207 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
208 attrs.Srcs = partitionedSrcs[cppSrcPartition]
209 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
210 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000211
Liz Kammer12615db2021-09-28 09:19:17 -0400212 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
213 // TODO(b/208815215): determine whether this is used and add support if necessary
214 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
215 }
216
Jingwen Chenbcf53042021-05-26 04:42:42 +0000217 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000218}
219
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400220// Convenience struct to hold all attributes parsed from prebuilt properties.
221type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000222 Src bazel.LabelAttribute
223 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400224}
225
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000226// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000227func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) prebuiltAttributes {
228 manySourceFileError := func(axis bazel.ConfigurationAxis, config string) {
229 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most one source file for %s %s\n", axis, config)
230 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400231 var srcLabelAttribute bazel.LabelAttribute
232
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000233 parseSrcs := func(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, srcs []string) {
234 if len(srcs) > 1 {
235 manySourceFileError(axis, config)
236 return
237 } else if len(srcs) == 0 {
238 return
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400239 }
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000240 if srcLabelAttribute.SelectValue(axis, config) != nil {
241 manySourceFileError(axis, config)
242 return
243 }
244
245 src := android.BazelLabelForModuleSrcSingle(ctx, srcs[0])
246 srcLabelAttribute.SetSelectValue(axis, config, src)
247 }
248
249 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
250 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
251 parseSrcs(ctx, axis, config, prebuiltLinkerProperties.Srcs)
252 }
253 })
254
255 var enabledLabelAttribute bazel.BoolAttribute
256 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
257 if props.Enabled != nil {
258 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
259 }
260 parseSrcs(ctx, axis, config, props.Srcs)
261 }
262
263 if isStatic {
264 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
265 if staticProperties, ok := props.(*StaticProperties); ok {
266 parseAttrs(axis, config, staticProperties.Static)
267 }
268 })
269 } else {
270 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
271 if sharedProperties, ok := props.(*SharedProperties); ok {
272 parseAttrs(axis, config, sharedProperties.Shared)
273 }
274 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400275 }
276
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400277 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000278 Src: srcLabelAttribute,
279 Enabled: enabledLabelAttribute,
280 }
281}
282
283func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
284 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
285 for config, props := range configToProps {
286 parseFunc(axis, config, props)
287 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400288 }
289}
290
Liz Kammere6583482021-10-19 13:56:10 -0400291type baseAttributes struct {
292 compilerAttributes
293 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400294
Cole Faust5fa4e962022-08-22 14:31:04 -0700295 // A combination of compilerAttributes.features and linkerAttributes.features
296 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400297 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400298 aidlDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400299}
300
Jingwen Chen107c0de2021-04-09 10:43:12 +0000301// Convenience struct to hold all attributes parsed from compiler properties.
302type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400303 // Options for all languages
304 copts bazel.StringListAttribute
305 // Assembly options and sources
306 asFlags bazel.StringListAttribute
307 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700308 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400309 // C options and sources
310 conlyFlags bazel.StringListAttribute
311 cSrcs bazel.LabelListAttribute
312 // C++ options and sources
313 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000314 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400315
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000316 // Lex sources and options
317 lSrcs bazel.LabelListAttribute
318 llSrcs bazel.LabelListAttribute
319 lexopts bazel.StringListAttribute
320
Liz Kammere6583482021-10-19 13:56:10 -0400321 hdrs bazel.LabelListAttribute
322
Chris Parsons2c788392021-08-10 11:58:07 -0400323 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000324
325 // Not affected by arch variants
326 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500327 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000328 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400329
330 localIncludes bazel.StringListAttribute
331 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400332
Liz Kammer1263d9b2021-12-10 14:28:20 -0500333 includes BazelIncludes
334
Liz Kammer12615db2021-09-28 09:19:17 -0400335 protoSrcs bazel.LabelListAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400336 aidlSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000337
338 stubsSymbolFile *string
339 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700340
341 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500342
343 suffix bazel.StringAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000344}
345
Liz Kammercac7f692021-12-16 14:19:32 -0500346type filterOutFn func(string) bool
347
348func filterOutStdFlag(flag string) bool {
349 return strings.HasPrefix(flag, "-std=")
350}
351
Alix1be00d42022-05-16 22:56:04 +0000352func filterOutClangUnknownCflags(flag string) bool {
353 for _, f := range config.ClangUnknownCflags {
354 if f == flag {
355 return true
356 }
357 }
358 return false
359}
360
361func parseCommandLineFlags(soongFlags []string, noCoptsTokenization bool, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400362 var result []string
363 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000364 skipFlag := false
365 for _, filter := range filterOut {
366 if filter != nil && filter(flag) {
367 skipFlag = true
368 }
369 }
370 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500371 continue
372 }
Liz Kammere6583482021-10-19 13:56:10 -0400373 // Soong's cflags can contain spaces, like `-include header.h`. For
374 // Bazel's copts, split them up to be compatible with the
375 // no_copts_tokenization feature.
Alix1be00d42022-05-16 22:56:04 +0000376 if noCoptsTokenization {
377 result = append(result, strings.Split(flag, " ")...)
378 } else {
379 // Soong's Version Script and Dynamic List Properties are added as flags
380 // to Bazel's linkopts using "($location label)" syntax.
381 // Splitting on spaces would separate this into two different flags
382 // "($ location" and "label)"
383 result = append(result, flag)
384 }
Liz Kammere6583482021-10-19 13:56:10 -0400385 }
386 return result
387}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000388
Jingwen Chen55bc8202021-11-02 06:40:51 +0000389func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400390 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
391 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
392 if srcsList, ok := parseSrcs(ctx, props); ok {
393 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400394 }
395
Liz Kammere6583482021-10-19 13:56:10 -0400396 localIncludeDirs := props.Local_include_dirs
397 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500398 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400399 if includeBuildDirectory(props.Include_build_directory) {
400 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400401 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000402 }
403
Liz Kammere6583482021-10-19 13:56:10 -0400404 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
405 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
406
Cole Faust5fa4e962022-08-22 14:31:04 -0700407 instructionSet := proptools.StringDefault(props.Instruction_set, "")
408 if instructionSet == "arm" {
409 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm", "-arm_isa_thumb"})
410 } else if instructionSet != "" && instructionSet != "thumb" {
411 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
412 }
413
Liz Kammercac7f692021-12-16 14:19:32 -0500414 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
415 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
416 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
417 // cases.
Alix1be00d42022-05-16 22:56:04 +0000418 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, true, filterOutStdFlag, filterOutClangUnknownCflags))
419 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, true, nil))
420 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, true, filterOutClangUnknownCflags))
421 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, true, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400422 ca.rtti.SetSelectValue(axis, config, props.Rtti)
423}
424
Jingwen Chen55bc8202021-11-02 06:40:51 +0000425func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000426 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
427 if stlProps, ok := props.(*StlProperties); ok {
428 if stlProps.Stl == nil {
429 return
430 }
431 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400432 stl := deduplicateStlInput(*stlProps.Stl)
433 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000434 } else if ca.stl != stlProps.Stl {
435 ctx.ModuleErrorf("Unsupported conversion: module with different stl for different variants: %s and %s", *ca.stl, stlProps.Stl)
Liz Kammer9abd62d2021-05-21 08:37:59 -0400436 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000437 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000438 })
Liz Kammere6583482021-10-19 13:56:10 -0400439}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000440
Jingwen Chen55bc8202021-11-02 06:40:51 +0000441func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400442 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400443 "Cflags": &ca.copts,
444 "Asflags": &ca.asFlags,
445 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400446 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400447 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000448 if productConfigProps, exists := productVariableProps[propName]; exists {
449 for productConfigProp, prop := range productConfigProps {
450 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400451 if !ok {
452 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
453 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000454 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
455 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400456 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400457 }
458 }
Liz Kammere6583482021-10-19 13:56:10 -0400459}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400460
Jingwen Chen55bc8202021-11-02 06:40:51 +0000461func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400462 ca.srcs.ResolveExcludes()
463 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
464
Liz Kammer12615db2021-09-28 09:19:17 -0400465 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400466 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400467
Liz Kammere6583482021-10-19 13:56:10 -0400468 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
477 ca.srcs = partitionedSrcs[cppSrcPartition]
478 ca.cSrcs = partitionedSrcs[cSrcPartition]
479 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700480 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000481 ca.lSrcs = partitionedSrcs[lSrcPartition]
482 ca.llSrcs = partitionedSrcs[llSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400483
484 ca.absoluteIncludes.DeduplicateAxesFromBase()
485 ca.localIncludes.DeduplicateAxesFromBase()
486}
487
488// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000489func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400490 anySrcs := false
491 // Add srcs-like dependencies such as generated files.
492 // First create a LabelList containing these dependencies, then merge the values with srcs.
493 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
494 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
495 anySrcs = true
496 }
497
498 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400499
Liz Kammere6583482021-10-19 13:56:10 -0400500 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
501 anySrcs = true
502 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400503
Liz Kammere6583482021-10-19 13:56:10 -0400504 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
505}
506
Vinh Tran9f6796a2022-08-16 13:10:31 -0400507// Given a name in srcs prop, check to see if the name references a filegroup
508// and the filegroup is converted to aidl_library
509func isConvertedToAidlLibrary(ctx android.BazelConversionPathContext, name string) bool {
510 if module, ok := ctx.ModuleFromName(name); ok {
511 if android.IsFilegroup(ctx, module) {
512 if fg, ok := module.(android.Bp2buildAidlLibrary); ok {
513 return fg.ShouldConvertToAidlLibrary(ctx)
514 }
515 }
516 }
517 return false
518}
519
Liz Kammera5a29de2022-05-25 23:19:37 -0400520func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
521 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500522 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
523 // Defaults are handled by the toolchain definition.
524 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400525 stdVal := proptools.StringDefault(std, defaultVal)
526 if stdVal == "experimental" || stdVal == defaultVal {
527 if stdVal == "experimental" {
528 stdVal = prefix + "_std_experimental"
529 }
530 if !useGnu {
531 stdVal += "_no_gnu"
532 }
533 } else if !useGnu {
534 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500535 }
536
Liz Kammera5a29de2022-05-25 23:19:37 -0400537 if stdVal == defaultVal {
538 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500539 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400540 return &stdVal
541}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500542
Liz Kammera5a29de2022-05-25 23:19:37 -0400543func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
544 useGnu := useGnuExtensions(gnu_extensions)
545
546 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400547}
548
Liz Kammer1263d9b2021-12-10 14:28:20 -0500549// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
550// is fully-qualified.
551// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
552func packageFromLabel(label string) (string, bool) {
553 split := strings.Split(label, ":")
554 if len(split) != 2 {
555 return "", false
556 }
557 if split[0] == "" {
558 return ".", false
559 }
560 // remove leading "//"
561 return split[0][2:], true
562}
563
564// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
565func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
566 for _, hdr := range labelList.Includes {
567 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
568 absolute = append(absolute, pkg)
569 } else if pkg != "" {
570 relative = append(relative, pkg)
571 }
572 }
573 return relative, absolute
574}
575
Cole Faust7071a052022-07-29 15:58:33 -0700576type YasmAttributes struct {
577 Srcs bazel.LabelListAttribute
578 Flags bazel.StringListAttribute
579 Include_dirs bazel.StringListAttribute
580}
581
582func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
583 if ca.asmSrcs.IsEmpty() {
584 return nil
585 }
586
587 // Yasm needs the include directories from both local_includes and
588 // export_include_dirs. We don't care about actually exporting them from the
589 // yasm rule though, because they will also be present on the cc_ rule that
590 // wraps this yasm rule.
591 includes := ca.localIncludes.Clone()
592 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
593 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
594 if len(flagExporterProperties.Export_include_dirs) > 0 {
595 x := bazel.StringListAttribute{}
596 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
597 includes.Append(x)
598 }
599 }
600 })
601
602 ctx.CreateBazelTargetModule(
603 bazel.BazelTargetModuleProperties{
604 Rule_class: "yasm",
605 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
606 },
607 android.CommonAttributes{Name: m.Name() + "_yasm"},
608 &YasmAttributes{
609 Srcs: ca.asmSrcs,
610 Flags: ca.asFlags,
611 Include_dirs: *includes,
612 })
613
614 // We only want to add a dependency on the _yasm target if there are asm
615 // sources in the current configuration. If there are unconfigured asm
616 // sources, always add the dependency. Otherwise, add the dependency only
617 // on the configuration axes and values that had asm sources.
618 if len(ca.asmSrcs.Value.Includes) > 0 {
619 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
620 }
621
622 ret := &bazel.LabelAttribute{}
623 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
624 for config := range ca.asmSrcs.ConfigurableValues[axis] {
625 ret.SetSelectValue(axis, config, bazel.Label{Label: ":" + m.Name() + "_yasm"})
626 }
627 }
628 return ret
629}
630
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000631// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400632func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400633 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
634 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000635 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400636
637 var implementationHdrs bazel.LabelListAttribute
638
639 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
640 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
641 for axis, configMap := range cp {
642 if _, ok := axisToConfigs[axis]; !ok {
643 axisToConfigs[axis] = map[string]bool{}
644 }
645 for config, _ := range configMap {
646 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400647 }
648 }
649 }
Liz Kammere6583482021-10-19 13:56:10 -0400650 allAxesAndConfigs(archVariantCompilerProps)
651 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000652 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400653
Liz Kammere6583482021-10-19 13:56:10 -0400654 compilerAttrs := compilerAttributes{}
655 linkerAttrs := linkerAttributes{}
656
657 for axis, configs := range axisToConfigs {
658 for config, _ := range configs {
659 var allHdrs []string
660 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
661 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000662 if baseCompilerProps.Lex != nil {
663 compilerAttrs.lexopts.SetSelectValue(axis, config, baseCompilerProps.Lex.Flags)
664 }
Liz Kammere6583482021-10-19 13:56:10 -0400665 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
666 }
667
668 var exportHdrs []string
669
670 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
671 exportHdrs = baseLinkerProps.Export_generated_headers
672
673 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
674 }
675 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
676 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
677 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500678
679 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
680 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
681 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
682
683 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
684 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
685 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400686
Liz Kammer1263d9b2021-12-10 14:28:20 -0500687 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400688
Liz Kammer1263d9b2021-12-10 14:28:20 -0500689 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
690 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400691
Liz Kammer1263d9b2021-12-10 14:28:20 -0500692 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000693
694 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
695 if axis == bazel.NoConfigAxis {
696 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
697 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
698 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500699 if suffix := libraryProps.Suffix; suffix != nil {
700 compilerAttrs.suffix.SetSelectValue(axis, config, suffix)
701 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000702 }
Liz Kammere6583482021-10-19 13:56:10 -0400703 }
704 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400705
Liz Kammere6583482021-10-19 13:56:10 -0400706 compilerAttrs.convertStlProps(ctx, module)
707 (&linkerAttrs).convertStripProps(ctx, module)
708
Yu Liu8d82ac52022-05-17 15:13:28 -0700709 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
710 !Bool(module.coverage.Properties.Native_coverage) {
711 // Native_coverage is arch neutral
712 (&linkerAttrs).features.Append(bazel.MakeStringListAttribute([]string{"-coverage"}))
713 }
714
Liz Kammere6583482021-10-19 13:56:10 -0400715 productVariableProps := android.ProductVariableProperties(ctx)
716
717 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
718 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
719
720 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500721 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400722
Cole Faust7071a052022-07-29 15:58:33 -0700723 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
724
Liz Kammer12615db2021-09-28 09:19:17 -0400725 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400726 aidlDep := bp2buildCcAidlLibrary(ctx, module, compilerAttrs.aidlSrcs)
Liz Kammer12615db2021-09-28 09:19:17 -0400727
728 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
729 // which. This will add the newly generated proto library to the appropriate attribute and nothing
730 // to the other
731 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
732 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400733 // TODO(b/243023967) Add aidlDep to implementationWholeArchiveDeps if aidl.export_aidl_headers is true
734 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
Liz Kammer12615db2021-09-28 09:19:17 -0400735
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000736 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
737 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
738 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
739
Cole Faust5fa4e962022-08-22 14:31:04 -0700740 features := compilerAttrs.features.Clone().Append(linkerAttrs.features)
741 features.DeduplicateAxesFromBase()
742
Liz Kammere6583482021-10-19 13:56:10 -0400743 return baseAttributes{
744 compilerAttrs,
745 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700746 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400747 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400748 aidlDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000749 }
750}
751
Vinh Tran9f6796a2022-08-16 13:10:31 -0400752func bp2buildAidlLibraries(
753 ctx android.Bp2buildMutatorContext,
754 m *Module,
755 aidlSrcs bazel.LabelListAttribute,
756) bazel.LabelList {
757 var aidlLibraries bazel.LabelList
758 var directAidlSrcs bazel.LabelList
759
760 // Make a list of labels that correspond to filegroups that are already converted to aidl_library
761 for _, aidlSrc := range aidlSrcs.Value.Includes {
762 src := aidlSrc.OriginalModuleName
763 if isConvertedToAidlLibrary(ctx, src) {
764 module, _ := ctx.ModuleFromName(src)
765 fg, _ := module.(android.Bp2buildAidlLibrary)
766 aidlLibraries.Add(&bazel.Label{
767 Label: fg.GetAidlLibraryLabel(ctx),
768 })
769 } else {
770 directAidlSrcs.Add(&aidlSrc)
771 }
772 }
773
774 if len(directAidlSrcs.Includes) > 0 {
775 aidlLibraryLabel := m.Name() + "_aidl_library"
776 ctx.CreateBazelTargetModule(
777 bazel.BazelTargetModuleProperties{
778 Rule_class: "aidl_library",
779 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
780 },
781 android.CommonAttributes{Name: aidlLibraryLabel},
782 &aidlLibraryAttributes{
783 Srcs: bazel.MakeLabelListAttribute(directAidlSrcs),
784 },
785 )
786 aidlLibraries.Add(&bazel.Label{
787 Label: ":" + aidlLibraryLabel,
788 })
789 }
790 return aidlLibraries
791}
792
793func bp2buildCcAidlLibrary(
794 ctx android.Bp2buildMutatorContext,
795 m *Module,
796 aidlSrcs bazel.LabelListAttribute,
797) *bazel.LabelAttribute {
798 suffix := "_cc_aidl_library"
799 ccAidlLibrarylabel := m.Name() + suffix
800
801 aidlLibraries := bp2buildAidlLibraries(ctx, m, aidlSrcs)
802
803 if aidlLibraries.IsEmpty() {
804 return nil
805 }
806
807 ctx.CreateBazelTargetModule(
808 bazel.BazelTargetModuleProperties{
809 Rule_class: "cc_aidl_library",
810 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
811 },
812 android.CommonAttributes{Name: ccAidlLibrarylabel},
813 &ccAidlLibraryAttributes{
814 Deps: bazel.MakeLabelListAttribute(aidlLibraries),
815 },
816 )
817
818 label := &bazel.LabelAttribute{
819 Value: &bazel.Label{
820 Label: ":" + ccAidlLibrarylabel,
821 },
822 }
823 return label
824}
825
Yu Liufc603162022-03-01 15:44:08 -0800826func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000827 return sdkAttributes{
828 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800829 Min_sdk_version: module.Properties.Min_sdk_version,
830 }
831}
832
833type sdkAttributes struct {
834 Sdk_version *string
835 Min_sdk_version *string
836}
837
Jingwen Chen107c0de2021-04-09 10:43:12 +0000838// Convenience struct to hold all attributes parsed from linker properties.
839type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500840 deps bazel.LabelListAttribute
841 implementationDeps bazel.LabelListAttribute
842 dynamicDeps bazel.LabelListAttribute
843 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -0700844 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -0500845 wholeArchiveDeps bazel.LabelListAttribute
846 implementationWholeArchiveDeps bazel.LabelListAttribute
847 systemDynamicDeps bazel.LabelListAttribute
848 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400849
Jingwen Chen6ada5892021-09-17 11:38:09 +0000850 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000851 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500852 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000853 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400854 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000855 stripKeepSymbols bazel.BoolAttribute
856 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
857 stripKeepSymbolsList bazel.StringListAttribute
858 stripAll bazel.BoolAttribute
859 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400860 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400861}
862
Liz Kammer54309532021-12-14 12:21:22 -0500863var (
864 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
865)
866
Jingwen Chen55bc8202021-11-02 06:40:51 +0000867func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400868 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
869 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400870
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400871 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
872 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammere6583482021-10-19 13:56:10 -0400873 // Excludes to parallel Soong:
874 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400875 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
876
Liz Kammere6583482021-10-19 13:56:10 -0400877 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400878
Liz Kammere6583482021-10-19 13:56:10 -0400879 headerLibs := android.FirstUniqueStrings(props.Header_libs)
880 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400881
Liz Kammere6583482021-10-19 13:56:10 -0400882 (&hDeps.export).Append(staticDeps.export)
883 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000884
Liz Kammere6583482021-10-19 13:56:10 -0400885 (&hDeps.implementation).Append(staticDeps.implementation)
886 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400887
Liz Kammere6583482021-10-19 13:56:10 -0400888 systemSharedLibs := props.System_shared_libs
889 // systemSharedLibs distinguishes between nil/empty list behavior:
890 // nil -> use default values
891 // empty list -> no values specified
892 if len(systemSharedLibs) > 0 {
893 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
894 }
895 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
896
897 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500898 excludeSharedLibs := props.Exclude_shared_libs
899 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
900 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
901 })
902 for _, el := range usedSystem {
903 if la.usedSystemDynamicDepAsDynamicDep == nil {
904 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
905 }
906 la.usedSystemDynamicDepAsDynamicDep[el] = true
907 }
908
Liz Kammere6583482021-10-19 13:56:10 -0400909 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
910 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
911 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Wei Li81852ca2022-07-27 00:22:06 -0700912 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
913 // If a dependency in la.implementationDynamicDeps has stubs, its stub variant should be
914 // used when the dependency is linked in a APEX. The dependencies in NoConfigAxis and
915 // OsConfigurationAxis/OsAndroid are grouped by having stubs or not, so Bazel select()
916 // statement can be used to choose source/stub variants of them.
917 depsWithStubs := []bazel.Label{}
918 for _, l := range sharedDeps.implementation.Includes {
919 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
920 if m, ok := dep.(*Module); ok && m.HasStubsVariants() {
921 depsWithStubs = append(depsWithStubs, l)
922 }
923 }
924 if len(depsWithStubs) > 0 {
925 implDynamicDeps := bazel.SubtractBazelLabelList(sharedDeps.implementation, bazel.MakeLabelList(depsWithStubs))
926 la.implementationDynamicDeps.SetSelectValue(axis, config, implDynamicDeps)
927
928 stubLibLabels := []bazel.Label{}
929 for _, l := range depsWithStubs {
930 l.Label = l.Label + "_stub_libs_current"
931 stubLibLabels = append(stubLibLabels, l)
932 }
933 inApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex)
934 nonApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex)
935 defaultSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
936 if axis == bazel.NoConfigAxis {
937 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
938 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
939 (&defaultSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
940 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, inApexSelectValue)
941 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, nonApexSelectValue)
942 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, defaultSelectValue)
943 } else if config == bazel.OsAndroid {
944 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
945 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
946 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, inApexSelectValue)
947 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, nonApexSelectValue)
948 }
949 }
950 }
Liz Kammere6583482021-10-19 13:56:10 -0400951
952 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
953 axisFeatures = append(axisFeatures, "disable_pack_relocations")
954 }
955
956 if Bool(props.Allow_undefined_symbols) {
957 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
958 }
959
960 var linkerFlags []string
961 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -0500962 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -0400963 // binaries remove static flag if -shared is in the linker flags
964 if isBinary && android.InList("-shared", linkerFlags) {
965 axisFeatures = append(axisFeatures, "-static_flag")
966 }
967 }
968 if props.Version_script != nil {
969 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
970 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
971 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
972 }
Alix773adaa2022-04-27 17:49:34 +0000973
974 if props.Dynamic_list != nil {
975 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
976 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
977 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
978 }
979
Alix1be00d42022-05-16 22:56:04 +0000980 la.linkopts.SetSelectValue(axis, config, parseCommandLineFlags(linkerFlags, false, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400981 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
982
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500983 if axis == bazel.NoConfigAxis {
984 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
985 }
986
Liz Kammere6583482021-10-19 13:56:10 -0400987 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
988 if props.crt() != nil {
989 if axis == bazel.NoConfigAxis {
990 la.linkCrt.SetSelectValue(axis, config, props.crt())
991 } else if axis == bazel.ArchConfigurationAxis {
992 ctx.ModuleErrorf("nocrt is not supported for arch variants")
993 }
994 }
995
996 if axisFeatures != nil {
997 la.features.SetSelectValue(axis, config, axisFeatures)
998 }
Cole Faust6b29f592022-08-09 09:50:56 -0700999
1000 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1001 if !runtimeDeps.IsEmpty() {
1002 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1003 }
Liz Kammere6583482021-10-19 13:56:10 -04001004}
1005
Jingwen Chen55bc8202021-11-02 06:40:51 +00001006func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001007 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1008 if stripProperties, ok := props.(*StripProperties); ok {
1009 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1010 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1011 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1012 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1013 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001014 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001015 })
Liz Kammere6583482021-10-19 13:56:10 -04001016}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001017
Jingwen Chen55bc8202021-11-02 06:40:51 +00001018func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001019
Liz Kammer47535c52021-06-02 16:02:22 -04001020 type productVarDep struct {
1021 // the name of the corresponding excludes field, if one exists
1022 excludesField string
1023 // reference to the bazel attribute that should be set for the given product variable config
1024 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001025
Jingwen Chen55bc8202021-11-02 06:40:51 +00001026 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001027 }
1028
Zi Wang0a8a1292022-08-30 06:27:01 +00001029 // an intermediate attribute that holds Header_libs info, and will be appended to
1030 // implementationDeps at the end, to solve the confliction that both header_libs
1031 // and static_libs use implementationDeps.
1032 var headerDeps bazel.LabelListAttribute
1033
Liz Kammer47535c52021-06-02 16:02:22 -04001034 productVarToDepFields := map[string]productVarDep{
1035 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001036 "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},
Zi Wang0a8a1292022-08-30 06:27:01 +00001039 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001040 }
1041
Liz Kammer47535c52021-06-02 16:02:22 -04001042 for name, dep := range productVarToDepFields {
1043 props, exists := productVariableProps[name]
1044 excludeProps, excludesExists := productVariableProps[dep.excludesField]
1045 // if neither an include or excludes property exists, then skip it
1046 if !exists && !excludesExists {
1047 continue
1048 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001049 // Collect all the configurations that an include or exclude property exists for.
1050 // We want to iterate all configurations rather than either the include or exclude because, for a
1051 // particular configuration, we may have either only an include or an exclude to handle.
1052 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
1053 for p := range props {
1054 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001055 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001056 for p := range excludeProps {
1057 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001058 }
1059
Jingwen Chen25825ca2021-11-15 12:28:43 +00001060 for productConfigProp := range productConfigProps {
1061 prop, includesExists := props[productConfigProp]
1062 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001063 var includes, excludes []string
1064 var ok bool
1065 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001066 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001067 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1068 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001069 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001070 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1071 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001072
Jingwen Chen58ff6802021-11-17 12:14:41 +00001073 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001074 dep.attribute.SetSelectValue(
1075 productConfigProp.ConfigurationAxis(),
1076 productConfigProp.SelectKey(),
1077 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1078 )
Liz Kammer47535c52021-06-02 16:02:22 -04001079 }
1080 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001081 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001082}
Liz Kammer47535c52021-06-02 16:02:22 -04001083
Liz Kammer54309532021-12-14 12:21:22 -05001084func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1085 // if system dynamic deps have the default value, any use of a system dynamic library used will
1086 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001087 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001088 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
1089 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001090 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
1091 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
1092 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001093 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1094 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
1095 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1096 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
1097 }
1098
Liz Kammere6583482021-10-19 13:56:10 -04001099 la.deps.ResolveExcludes()
1100 la.implementationDeps.ResolveExcludes()
1101 la.dynamicDeps.ResolveExcludes()
1102 la.implementationDynamicDeps.ResolveExcludes()
1103 la.wholeArchiveDeps.ResolveExcludes()
1104 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001105
Jingwen Chen91220d72021-03-24 02:18:33 -04001106}
1107
Jingwen Chened9c17d2021-04-13 07:14:55 +00001108// 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.
1118func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001119 var relativePaths []string
1120 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001121 // 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 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001126 relativePaths = append(relativePaths, relativePath)
1127 }
1128 return relativePaths
1129}
1130
Liz Kammer5fad5012021-09-09 14:08:21 -04001131// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1132// attributes.
1133type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001134 AbsoluteIncludes bazel.StringListAttribute
1135 Includes bazel.StringListAttribute
1136 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001137}
1138
Liz Kammer54549442022-05-11 13:55:06 -04001139func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001140 var exported BazelIncludes
1141 if includes != nil {
1142 exported = *includes
1143 } else {
1144 exported = BazelIncludes{}
1145 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001146 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1147 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1148 if len(flagExporterProperties.Export_include_dirs) > 0 {
1149 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1150 }
1151 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1152 exported.SystemIncludes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.SystemIncludes.SelectValue(axis, config), flagExporterProperties.Export_system_include_dirs...)))
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001153 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001154 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001155 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001156 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001157 exported.Includes.DeduplicateAxesFromBase()
1158 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001159
Liz Kammer5fad5012021-09-09 14:08:21 -04001160 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001161}
Chris Parsons953b3562021-09-20 15:14:39 -04001162
Jingwen Chen55bc8202021-11-02 06:40:51 +00001163func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001164 label := android.BazelModuleLabel(ctx, m)
Chris Parsonsad876012022-08-20 14:48:32 -04001165 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GetBp2BuildAllowList().GenerateCcLibraryStaticOnly(m.Name()) {
Liz Kammer35ca77e2021-12-22 15:31:40 -05001166 label += "_bp2build_cc_library_static"
Chris Parsons953b3562021-09-20 15:14:39 -04001167 }
1168 return label
1169}
1170
Jingwen Chen55bc8202021-11-02 06:40:51 +00001171func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001172 // cc_library, at it's root name, propagates the shared library, which depends on the static
1173 // library.
1174 return android.BazelModuleLabel(ctx, m)
1175}
1176
Jingwen Chen55bc8202021-11-02 06:40:51 +00001177func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001178 label := bazelLabelForStaticModule(ctx, m)
1179 if aModule, ok := m.(android.Module); ok {
1180 if android.IsModulePrebuilt(aModule) {
1181 label += "_alwayslink"
1182 }
1183 }
1184 return label
1185}
1186
Jingwen Chen55bc8202021-11-02 06:40:51 +00001187func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001188 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1189}
1190
Jingwen Chen55bc8202021-11-02 06:40:51 +00001191func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001192 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1193}
1194
Jingwen Chen55bc8202021-11-02 06:40:51 +00001195func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001196 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1197}
1198
Jingwen Chen55bc8202021-11-02 06:40:51 +00001199func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001200 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1201}
1202
Jingwen Chen55bc8202021-11-02 06:40:51 +00001203func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001204 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1205}
1206
Jingwen Chen55bc8202021-11-02 06:40:51 +00001207func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001208 // This is not elegant, but bp2build's shared library targets only propagate
1209 // their header information as part of the normal C++ provider.
1210 return bazelLabelForSharedDeps(ctx, modules)
1211}
1212
Zi Wang0a8a1292022-08-30 06:27:01 +00001213func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1214 // This is only used when product_variable header_libs is processed, to follow
1215 // the pattern of depResolutionFunc
1216 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1217}
1218
Jingwen Chen55bc8202021-11-02 06:40:51 +00001219func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001220 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1221}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001222
1223type binaryLinkerAttrs struct {
1224 Linkshared *bool
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001225 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001226}
1227
Jingwen Chen55bc8202021-11-02 06:40:51 +00001228func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001229 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001230 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1231 linkerProps := props.(*BinaryLinkerProperties)
1232 staticExecutable := linkerProps.Static_executable
1233 if axis == bazel.NoConfigAxis {
1234 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1235 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001236 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001237 } else if staticExecutable != nil {
1238 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1239 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1240 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001241 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001242 if suffix := linkerProps.Suffix; suffix != nil {
1243 attrs.Suffix.SetSelectValue(axis, config, suffix)
1244 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001245 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001246
1247 return attrs
1248}