blob: 868ff0db5b042f4daa7c4918c9a9930273b5aeeb [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 (
Trevor Radcliffecee4e052022-09-06 19:31:25 +000031 cSrcPartition = "c"
32 asSrcPartition = "as"
33 asmSrcPartition = "asm"
34 lSrcPartition = "l"
35 llSrcPartition = "ll"
36 cppSrcPartition = "cpp"
37 protoSrcPartition = "proto"
38 aidlSrcPartition = "aidl"
39 syspropSrcPartition = "sysprop"
Liz Kammer91487d42022-09-13 11:27:11 -040040
41 stubsSuffix = "_stub_libs_current"
Liz Kammerae3994e2021-10-19 09:45:48 -040042)
43
Liz Kammer2222c6b2021-05-24 15:41:47 -040044// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000045// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040046type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040047 Srcs bazel.LabelListAttribute
48 Srcs_c bazel.LabelListAttribute
49 Srcs_as bazel.LabelListAttribute
50 Srcs_aidl bazel.LabelListAttribute
51 Hdrs bazel.LabelListAttribute
52 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000053
Liz Kammer12615db2021-09-28 09:19:17 -040054 Deps bazel.LabelListAttribute
55 Implementation_deps bazel.LabelListAttribute
56 Dynamic_deps bazel.LabelListAttribute
57 Implementation_dynamic_deps bazel.LabelListAttribute
58 Whole_archive_deps bazel.LabelListAttribute
59 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070060 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040061
62 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050063
64 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080065
Yu Liu8d82ac52022-05-17 15:13:28 -070066 Native_coverage bazel.BoolAttribute
67
Yu Liufc603162022-03-01 15:44:08 -080068 sdkAttributes
Jingwen Chen53681ef2021-04-29 08:15:13 +000069}
70
Sam Delmericoc7681022022-02-04 21:01:20 +000071// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +000072func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -040073 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
74 // macro.
75 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -040076 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
77
78 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -040079 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -040080 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
81 return labelStr, false
82 }
Yu Liu2aa806b2022-09-01 11:54:47 -070083 // If the filegroup is already converted to aidl_library or proto_library,
84 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
85 fg, _ := m.(android.FileGroupAsLibrary)
86 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -040087 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000088 }
Liz Kammer12615db2021-09-28 09:19:17 -040089 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040090 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000091 }
92
Liz Kammer57e2e7a2021-09-20 12:55:02 -040093 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +000094 labels := bazel.LabelPartitions{
95 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -050096 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
97 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -070098 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -040099 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000100 // TODO(http://b/231968910): If there is ever a filegroup target that
101 // contains .l or .ll files we will need to find a way to add a
102 // LabelMapper for these that identifies these filegroups and
103 // converts them appropriately
104 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
105 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400106 // C++ is the "catch-all" group, and comprises generated sources because we don't
107 // know the language of these sources until the genrule is executed.
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000108 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
109 syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
Sam Delmericoc7681022022-02-04 21:01:20 +0000110 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000111
Sam Delmericoc7681022022-02-04 21:01:20 +0000112 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000113}
114
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000115// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000116func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000117 lib, ok := module.compiler.(*libraryDecorator)
118 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400119 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000120 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000121 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
122}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000123
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000124// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000125func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000126 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000127}
128
129// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000130func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000131 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400132}
133
Liz Kammer7a210ac2021-09-22 15:52:58 -0400134type depsPartition struct {
135 export bazel.LabelList
136 implementation bazel.LabelList
137}
138
Jingwen Chen55bc8202021-11-02 06:40:51 +0000139type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400140
Jingwen Chen55bc8202021-11-02 06:40:51 +0000141func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400142 if !exportsDeps {
143 return depsPartition{
144 implementation: fn(ctx, allDeps),
145 }
146 }
147
Liz Kammer7a210ac2021-09-22 15:52:58 -0400148 implementation, export := android.FilterList(allDeps, exportedDeps)
149
150 return depsPartition{
151 export: fn(ctx, export),
152 implementation: fn(ctx, implementation),
153 }
154}
155
Jingwen Chen55bc8202021-11-02 06:40:51 +0000156type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400157
Jingwen Chen55bc8202021-11-02 06:40:51 +0000158func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400159 if !exportsDeps {
160 return depsPartition{
161 implementation: fn(ctx, allDeps, excludes),
162 }
163 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400164 implementation, export := android.FilterList(allDeps, exportedDeps)
165
166 return depsPartition{
167 export: fn(ctx, export, excludes),
168 implementation: fn(ctx, implementation, excludes),
169 }
170}
171
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000172// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000173func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400174 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000175
Liz Kammer9abd62d2021-05-21 08:37:59 -0400176 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000177 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000178 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400179 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400180
Liz Kammer2b8004b2021-10-04 13:55:44 -0400181 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400182 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
183 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
184
Liz Kammer2b8004b2021-10-04 13:55:44 -0400185 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400186 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
187 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
188
189 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500190 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000191 }
Liz Kammer135bf552021-08-11 10:46:06 -0400192 // system_dynamic_deps distinguishes between nil/empty list behavior:
193 // nil -> use default values
194 // empty list -> no values specified
195 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000196
197 if isStatic {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000198 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
199 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
200 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000201 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000202 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000203 } else {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000204 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
205 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
206 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000207 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000208 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000209 }
210
Liz Kammerae3994e2021-10-19 09:45:48 -0400211 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
212 attrs.Srcs = partitionedSrcs[cppSrcPartition]
213 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
214 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000215
Liz Kammer12615db2021-09-28 09:19:17 -0400216 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
217 // TODO(b/208815215): determine whether this is used and add support if necessary
218 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
219 }
220
Jingwen Chenbcf53042021-05-26 04:42:42 +0000221 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000222}
223
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400224// Convenience struct to hold all attributes parsed from prebuilt properties.
225type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000226 Src bazel.LabelAttribute
227 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400228}
229
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000230// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000231func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) prebuiltAttributes {
232 manySourceFileError := func(axis bazel.ConfigurationAxis, config string) {
233 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most one source file for %s %s\n", axis, config)
234 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400235 var srcLabelAttribute bazel.LabelAttribute
236
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000237 parseSrcs := func(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, srcs []string) {
238 if len(srcs) > 1 {
239 manySourceFileError(axis, config)
240 return
241 } else if len(srcs) == 0 {
242 return
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400243 }
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000244 if srcLabelAttribute.SelectValue(axis, config) != nil {
245 manySourceFileError(axis, config)
246 return
247 }
248
249 src := android.BazelLabelForModuleSrcSingle(ctx, srcs[0])
250 srcLabelAttribute.SetSelectValue(axis, config, src)
251 }
252
253 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
254 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
255 parseSrcs(ctx, axis, config, prebuiltLinkerProperties.Srcs)
256 }
257 })
258
259 var enabledLabelAttribute bazel.BoolAttribute
260 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
261 if props.Enabled != nil {
262 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
263 }
264 parseSrcs(ctx, axis, config, props.Srcs)
265 }
266
267 if isStatic {
268 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
269 if staticProperties, ok := props.(*StaticProperties); ok {
270 parseAttrs(axis, config, staticProperties.Static)
271 }
272 })
273 } else {
274 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
275 if sharedProperties, ok := props.(*SharedProperties); ok {
276 parseAttrs(axis, config, sharedProperties.Shared)
277 }
278 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400279 }
280
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400281 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000282 Src: srcLabelAttribute,
283 Enabled: enabledLabelAttribute,
284 }
285}
286
287func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
288 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
289 for config, props := range configToProps {
290 parseFunc(axis, config, props)
291 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400292 }
293}
294
Liz Kammere6583482021-10-19 13:56:10 -0400295type baseAttributes struct {
296 compilerAttributes
297 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400298
Cole Faust5fa4e962022-08-22 14:31:04 -0700299 // A combination of compilerAttributes.features and linkerAttributes.features
300 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400301 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400302 aidlDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400303}
304
Jingwen Chen107c0de2021-04-09 10:43:12 +0000305// Convenience struct to hold all attributes parsed from compiler properties.
306type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400307 // Options for all languages
308 copts bazel.StringListAttribute
309 // Assembly options and sources
310 asFlags bazel.StringListAttribute
311 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700312 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400313 // C options and sources
314 conlyFlags bazel.StringListAttribute
315 cSrcs bazel.LabelListAttribute
316 // C++ options and sources
317 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000318 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400319
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000320 // Lex sources and options
321 lSrcs bazel.LabelListAttribute
322 llSrcs bazel.LabelListAttribute
323 lexopts bazel.StringListAttribute
324
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000325 // Sysprop sources
326 syspropSrcs bazel.LabelListAttribute
327
Liz Kammere6583482021-10-19 13:56:10 -0400328 hdrs bazel.LabelListAttribute
329
Chris Parsons2c788392021-08-10 11:58:07 -0400330 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000331
332 // Not affected by arch variants
333 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500334 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000335 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400336
337 localIncludes bazel.StringListAttribute
338 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400339
Liz Kammer1263d9b2021-12-10 14:28:20 -0500340 includes BazelIncludes
341
Liz Kammer12615db2021-09-28 09:19:17 -0400342 protoSrcs bazel.LabelListAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400343 aidlSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000344
345 stubsSymbolFile *string
346 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700347
348 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500349
350 suffix bazel.StringAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000351}
352
Liz Kammercac7f692021-12-16 14:19:32 -0500353type filterOutFn func(string) bool
354
355func filterOutStdFlag(flag string) bool {
356 return strings.HasPrefix(flag, "-std=")
357}
358
Alix1be00d42022-05-16 22:56:04 +0000359func filterOutClangUnknownCflags(flag string) bool {
360 for _, f := range config.ClangUnknownCflags {
361 if f == flag {
362 return true
363 }
364 }
365 return false
366}
367
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000368func parseCommandLineFlags(soongFlags []string, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400369 var result []string
370 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000371 skipFlag := false
372 for _, filter := range filterOut {
373 if filter != nil && filter(flag) {
374 skipFlag = true
375 }
376 }
377 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500378 continue
379 }
Liz Kammere6583482021-10-19 13:56:10 -0400380 // Soong's cflags can contain spaces, like `-include header.h`. For
381 // Bazel's copts, split them up to be compatible with the
382 // no_copts_tokenization feature.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000383 result = append(result, strings.Split(flag, " ")...)
Liz Kammere6583482021-10-19 13:56:10 -0400384 }
385 return result
386}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000387
Jingwen Chen55bc8202021-11-02 06:40:51 +0000388func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400389 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
390 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
391 if srcsList, ok := parseSrcs(ctx, props); ok {
392 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400393 }
394
Liz Kammere6583482021-10-19 13:56:10 -0400395 localIncludeDirs := props.Local_include_dirs
396 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500397 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400398 if includeBuildDirectory(props.Include_build_directory) {
399 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400400 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000401 }
402
Liz Kammere6583482021-10-19 13:56:10 -0400403 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
404 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
405
Cole Faust5fa4e962022-08-22 14:31:04 -0700406 instructionSet := proptools.StringDefault(props.Instruction_set, "")
407 if instructionSet == "arm" {
408 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm", "-arm_isa_thumb"})
409 } else if instructionSet != "" && instructionSet != "thumb" {
410 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
411 }
412
Liz Kammercac7f692021-12-16 14:19:32 -0500413 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
414 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
415 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
416 // cases.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000417 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutClangUnknownCflags))
418 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
419 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, filterOutClangUnknownCflags))
420 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400421 ca.rtti.SetSelectValue(axis, config, props.Rtti)
422}
423
Jingwen Chen55bc8202021-11-02 06:40:51 +0000424func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000425 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
426 if stlProps, ok := props.(*StlProperties); ok {
427 if stlProps.Stl == nil {
428 return
429 }
430 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400431 stl := deduplicateStlInput(*stlProps.Stl)
432 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000433 } else if ca.stl != stlProps.Stl {
434 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 -0400435 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000436 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000437 })
Liz Kammere6583482021-10-19 13:56:10 -0400438}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000439
Jingwen Chen55bc8202021-11-02 06:40:51 +0000440func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400441 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400442 "Cflags": &ca.copts,
443 "Asflags": &ca.asFlags,
444 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400445 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400446 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000447 if productConfigProps, exists := productVariableProps[propName]; exists {
448 for productConfigProp, prop := range productConfigProps {
449 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400450 if !ok {
451 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
452 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000453 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
454 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400455 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400456 }
457 }
Liz Kammere6583482021-10-19 13:56:10 -0400458}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400459
Jingwen Chen55bc8202021-11-02 06:40:51 +0000460func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400461 ca.srcs.ResolveExcludes()
462 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
463
Liz Kammer12615db2021-09-28 09:19:17 -0400464 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400465 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400466
Liz Kammere6583482021-10-19 13:56:10 -0400467 for p, lla := range partitionedSrcs {
468 // if there are no sources, there is no need for headers
469 if lla.IsEmpty() {
470 continue
471 }
472 lla.Append(implementationHdrs)
473 partitionedSrcs[p] = lla
474 }
475
476 ca.srcs = partitionedSrcs[cppSrcPartition]
477 ca.cSrcs = partitionedSrcs[cSrcPartition]
478 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700479 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000480 ca.lSrcs = partitionedSrcs[lSrcPartition]
481 ca.llSrcs = partitionedSrcs[llSrcPartition]
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000482 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
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
Liz Kammera5a29de2022-05-25 23:19:37 -0400507func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
508 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500509 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
510 // Defaults are handled by the toolchain definition.
511 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400512 stdVal := proptools.StringDefault(std, defaultVal)
513 if stdVal == "experimental" || stdVal == defaultVal {
514 if stdVal == "experimental" {
515 stdVal = prefix + "_std_experimental"
516 }
517 if !useGnu {
518 stdVal += "_no_gnu"
519 }
520 } else if !useGnu {
521 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500522 }
523
Liz Kammera5a29de2022-05-25 23:19:37 -0400524 if stdVal == defaultVal {
525 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500526 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400527 return &stdVal
528}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500529
Liz Kammera5a29de2022-05-25 23:19:37 -0400530func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
531 useGnu := useGnuExtensions(gnu_extensions)
532
533 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400534}
535
Liz Kammer1263d9b2021-12-10 14:28:20 -0500536// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
537// is fully-qualified.
538// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
539func packageFromLabel(label string) (string, bool) {
540 split := strings.Split(label, ":")
541 if len(split) != 2 {
542 return "", false
543 }
544 if split[0] == "" {
545 return ".", false
546 }
547 // remove leading "//"
548 return split[0][2:], true
549}
550
551// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
552func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
553 for _, hdr := range labelList.Includes {
554 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
555 absolute = append(absolute, pkg)
556 } else if pkg != "" {
557 relative = append(relative, pkg)
558 }
559 }
560 return relative, absolute
561}
562
Cole Faust7071a052022-07-29 15:58:33 -0700563type YasmAttributes struct {
564 Srcs bazel.LabelListAttribute
565 Flags bazel.StringListAttribute
566 Include_dirs bazel.StringListAttribute
567}
568
569func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
570 if ca.asmSrcs.IsEmpty() {
571 return nil
572 }
573
574 // Yasm needs the include directories from both local_includes and
575 // export_include_dirs. We don't care about actually exporting them from the
576 // yasm rule though, because they will also be present on the cc_ rule that
577 // wraps this yasm rule.
578 includes := ca.localIncludes.Clone()
579 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
580 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
581 if len(flagExporterProperties.Export_include_dirs) > 0 {
582 x := bazel.StringListAttribute{}
583 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
584 includes.Append(x)
585 }
586 }
587 })
588
589 ctx.CreateBazelTargetModule(
590 bazel.BazelTargetModuleProperties{
591 Rule_class: "yasm",
592 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
593 },
594 android.CommonAttributes{Name: m.Name() + "_yasm"},
595 &YasmAttributes{
596 Srcs: ca.asmSrcs,
597 Flags: ca.asFlags,
598 Include_dirs: *includes,
599 })
600
601 // We only want to add a dependency on the _yasm target if there are asm
602 // sources in the current configuration. If there are unconfigured asm
603 // sources, always add the dependency. Otherwise, add the dependency only
604 // on the configuration axes and values that had asm sources.
605 if len(ca.asmSrcs.Value.Includes) > 0 {
606 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
607 }
608
609 ret := &bazel.LabelAttribute{}
610 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
611 for config := range ca.asmSrcs.ConfigurableValues[axis] {
612 ret.SetSelectValue(axis, config, bazel.Label{Label: ":" + m.Name() + "_yasm"})
613 }
614 }
615 return ret
616}
617
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000618// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400619func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400620 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
621 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000622 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400623
624 var implementationHdrs bazel.LabelListAttribute
625
626 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
627 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
628 for axis, configMap := range cp {
629 if _, ok := axisToConfigs[axis]; !ok {
630 axisToConfigs[axis] = map[string]bool{}
631 }
632 for config, _ := range configMap {
633 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400634 }
635 }
636 }
Liz Kammere6583482021-10-19 13:56:10 -0400637 allAxesAndConfigs(archVariantCompilerProps)
638 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000639 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400640
Liz Kammere6583482021-10-19 13:56:10 -0400641 compilerAttrs := compilerAttributes{}
642 linkerAttrs := linkerAttributes{}
643
644 for axis, configs := range axisToConfigs {
645 for config, _ := range configs {
646 var allHdrs []string
647 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
648 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000649 if baseCompilerProps.Lex != nil {
650 compilerAttrs.lexopts.SetSelectValue(axis, config, baseCompilerProps.Lex.Flags)
651 }
Liz Kammere6583482021-10-19 13:56:10 -0400652 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
653 }
654
655 var exportHdrs []string
656
657 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
658 exportHdrs = baseLinkerProps.Export_generated_headers
659
660 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
661 }
662 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
663 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
664 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500665
666 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
667 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
668 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
669
670 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
671 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
672 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400673
Liz Kammer1263d9b2021-12-10 14:28:20 -0500674 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400675
Liz Kammer1263d9b2021-12-10 14:28:20 -0500676 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
677 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400678
Liz Kammer1263d9b2021-12-10 14:28:20 -0500679 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000680
681 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
682 if axis == bazel.NoConfigAxis {
683 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
684 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
685 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500686 if suffix := libraryProps.Suffix; suffix != nil {
687 compilerAttrs.suffix.SetSelectValue(axis, config, suffix)
688 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000689 }
Liz Kammere6583482021-10-19 13:56:10 -0400690 }
691 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400692
Liz Kammere6583482021-10-19 13:56:10 -0400693 compilerAttrs.convertStlProps(ctx, module)
694 (&linkerAttrs).convertStripProps(ctx, module)
695
Yu Liu8d82ac52022-05-17 15:13:28 -0700696 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
697 !Bool(module.coverage.Properties.Native_coverage) {
698 // Native_coverage is arch neutral
699 (&linkerAttrs).features.Append(bazel.MakeStringListAttribute([]string{"-coverage"}))
700 }
701
Liz Kammere6583482021-10-19 13:56:10 -0400702 productVariableProps := android.ProductVariableProperties(ctx)
703
704 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
705 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
706
707 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500708 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400709
Cole Faust7071a052022-07-29 15:58:33 -0700710 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
711
Liz Kammer12615db2021-09-28 09:19:17 -0400712 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
713
714 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
715 // which. This will add the newly generated proto library to the appropriate attribute and nothing
716 // to the other
717 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
718 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400719
Vinh Tran395a1e92022-09-16 18:27:29 -0400720 aidlDep := bp2buildCcAidlLibrary(ctx, module, compilerAttrs.aidlSrcs, linkerAttrs)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400721 if aidlDep != nil {
722 if lib, ok := module.linker.(*libraryDecorator); ok {
723 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
724 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
725 } else {
726 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
727 }
728 }
729 }
Liz Kammer12615db2021-09-28 09:19:17 -0400730
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000731 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
732 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
733 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
734
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000735 if !compilerAttrs.syspropSrcs.IsEmpty() {
736 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
737 }
738
Cole Faust5fa4e962022-08-22 14:31:04 -0700739 features := compilerAttrs.features.Clone().Append(linkerAttrs.features)
740 features.DeduplicateAxesFromBase()
741
Liz Kammere6583482021-10-19 13:56:10 -0400742 return baseAttributes{
743 compilerAttrs,
744 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700745 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400746 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400747 aidlDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000748 }
749}
750
Vinh Tran9f6796a2022-08-16 13:10:31 -0400751func bp2buildCcAidlLibrary(
752 ctx android.Bp2buildMutatorContext,
753 m *Module,
Vinh Trana3b8b782022-09-14 11:40:24 -0400754 aidlLabelList bazel.LabelListAttribute,
Vinh Tran395a1e92022-09-16 18:27:29 -0400755 linkerAttrs linkerAttributes,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400756) *bazel.LabelAttribute {
Vinh Trana3b8b782022-09-14 11:40:24 -0400757 if !aidlLabelList.IsEmpty() {
758 aidlLibs, aidlSrcs := aidlLabelList.Partition(func(src bazel.Label) bool {
759 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
760 fg.ShouldConvertToAidlLibrary(ctx) {
761 return true
762 }
763 return false
764 })
Vinh Tran9f6796a2022-08-16 13:10:31 -0400765
Vinh Trana3b8b782022-09-14 11:40:24 -0400766 if !aidlSrcs.IsEmpty() {
767 aidlLibName := m.Name() + "_aidl_library"
768 ctx.CreateBazelTargetModule(
769 bazel.BazelTargetModuleProperties{
770 Rule_class: "aidl_library",
771 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
772 },
773 android.CommonAttributes{Name: aidlLibName},
774 &aidlLibraryAttributes{
775 Srcs: aidlSrcs,
776 },
777 )
778 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
779 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400780
Vinh Trana3b8b782022-09-14 11:40:24 -0400781 if !aidlLibs.IsEmpty() {
782 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
Vinh Tran395a1e92022-09-16 18:27:29 -0400783 // Since cc_aidl_library only needs the dynamic deps (aka shared libs) from the parent cc library for compiling,
784 // we err on the side of not re-exporting the headers of the dynamic deps from cc_aidl_lirary
785 // because the parent cc library already has all the dynamic deps
786 implementationDynamicDeps := bazel.MakeLabelListAttribute(
787 bazel.AppendBazelLabelLists(
788 linkerAttrs.dynamicDeps.Value,
789 linkerAttrs.implementationDynamicDeps.Value,
790 ),
791 )
792
Vinh Trana3b8b782022-09-14 11:40:24 -0400793 ctx.CreateBazelTargetModule(
794 bazel.BazelTargetModuleProperties{
795 Rule_class: "cc_aidl_library",
796 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
797 },
798 android.CommonAttributes{Name: ccAidlLibrarylabel},
799 &ccAidlLibraryAttributes{
Vinh Tran395a1e92022-09-16 18:27:29 -0400800 Deps: aidlLibs,
801 Implementation_dynamic_deps: implementationDynamicDeps,
Vinh Trana3b8b782022-09-14 11:40:24 -0400802 },
803 )
804 label := &bazel.LabelAttribute{
805 Value: &bazel.Label{
806 Label: ":" + ccAidlLibrarylabel,
807 },
808 }
809 return label
810 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400811 }
812
Vinh Trana3b8b782022-09-14 11:40:24 -0400813 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -0400814}
815
Yu Liufc603162022-03-01 15:44:08 -0800816func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000817 return sdkAttributes{
818 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800819 Min_sdk_version: module.Properties.Min_sdk_version,
820 }
821}
822
823type sdkAttributes struct {
824 Sdk_version *string
825 Min_sdk_version *string
826}
827
Jingwen Chen107c0de2021-04-09 10:43:12 +0000828// Convenience struct to hold all attributes parsed from linker properties.
829type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500830 deps bazel.LabelListAttribute
831 implementationDeps bazel.LabelListAttribute
832 dynamicDeps bazel.LabelListAttribute
833 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -0700834 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -0500835 wholeArchiveDeps bazel.LabelListAttribute
836 implementationWholeArchiveDeps bazel.LabelListAttribute
837 systemDynamicDeps bazel.LabelListAttribute
838 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400839
Jingwen Chen6ada5892021-09-17 11:38:09 +0000840 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000841 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500842 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000843 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400844 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000845 stripKeepSymbols bazel.BoolAttribute
846 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
847 stripKeepSymbolsList bazel.StringListAttribute
848 stripAll bazel.BoolAttribute
849 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400850 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400851}
852
Liz Kammer54309532021-12-14 12:21:22 -0500853var (
854 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -0400855 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -0500856)
857
Vinh Tran85fb07c2022-09-16 16:17:48 -0400858// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
859// since all libs are already excluded by default
860func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, isBinary bool, props *BaseLinkerProperties) {
861 sharedLibsForNonApex := maybePartitionExportedAndImplementationsDeps(
862 ctx,
863 true,
864 props.Target.Apex.Exclude_shared_libs,
865 props.Export_shared_lib_headers,
866 bazelLabelForSharedDeps,
867 )
868 dynamicDeps := la.dynamicDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
869 implDynamicDeps := la.implementationDynamicDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
870 (&dynamicDeps).Append(sharedLibsForNonApex.export)
871 (&implDynamicDeps).Append(sharedLibsForNonApex.implementation)
872 la.dynamicDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, dynamicDeps)
873 la.implementationDynamicDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, implDynamicDeps)
874
875 staticLibsForNonApex := maybePartitionExportedAndImplementationsDeps(
876 ctx,
877 !isBinary,
878 props.Target.Apex.Exclude_static_libs,
879 props.Export_static_lib_headers,
880 bazelLabelForSharedDeps,
881 )
882 deps := la.deps.SelectValue(bazel.InApexAxis, bazel.NonApex)
883 implDeps := la.implementationDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
884 (&deps).Append(staticLibsForNonApex.export)
885 (&implDeps).Append(staticLibsForNonApex.implementation)
886 la.deps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, deps)
887 la.implementationDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, implDeps)
888}
889
Jingwen Chen55bc8202021-11-02 06:40:51 +0000890func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400891 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
892 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400893
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400894 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -0400895 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
896 if axis == bazel.NoConfigAxis {
897 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
898 if proptools.Bool(props.Use_version_lib) {
899 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
900 // remove from static libs so there is no duplicate dependency
901 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
902 // only add the dep if it is not in progress
903 if !versionLibAlreadyInDeps {
904 if isBinary {
905 wholeStaticLibs = append(wholeStaticLibs, versionLib)
906 } else {
907 la.implementationWholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, []string{versionLib}, props.Exclude_static_libs))
908 }
909 }
910 }
911 }
912
Liz Kammere6583482021-10-19 13:56:10 -0400913 // Excludes to parallel Soong:
914 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
Liz Kammerbaced712022-09-16 09:01:29 -0400915 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400916
Vinh Tran85fb07c2022-09-16 16:17:48 -0400917 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
918 ctx,
919 !isBinary,
920 staticLibs,
921 // Exclude static libs in Exclude_static_libs and Target.Apex.Exclude_static_libs props
922 append(props.Exclude_static_libs, props.Target.Apex.Exclude_static_libs...),
923 props.Export_static_lib_headers,
924 bazelLabelForStaticDepsExcludes,
925 )
Liz Kammer7a210ac2021-09-22 15:52:58 -0400926
Liz Kammere6583482021-10-19 13:56:10 -0400927 headerLibs := android.FirstUniqueStrings(props.Header_libs)
928 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400929
Liz Kammere6583482021-10-19 13:56:10 -0400930 (&hDeps.export).Append(staticDeps.export)
931 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000932
Liz Kammere6583482021-10-19 13:56:10 -0400933 (&hDeps.implementation).Append(staticDeps.implementation)
934 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400935
Liz Kammere6583482021-10-19 13:56:10 -0400936 systemSharedLibs := props.System_shared_libs
937 // systemSharedLibs distinguishes between nil/empty list behavior:
938 // nil -> use default values
939 // empty list -> no values specified
940 if len(systemSharedLibs) > 0 {
941 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
942 }
943 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
944
945 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500946 excludeSharedLibs := props.Exclude_shared_libs
947 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
948 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
949 })
950 for _, el := range usedSystem {
951 if la.usedSystemDynamicDepAsDynamicDep == nil {
952 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
953 }
954 la.usedSystemDynamicDepAsDynamicDep[el] = true
955 }
956
Vinh Tran85fb07c2022-09-16 16:17:48 -0400957 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
958 ctx,
959 !isBinary,
960 sharedLibs,
961 // Exclude shared libs in Exclude_shared_libs and Target.Apex.Exclude_shared_libs props
962 append(props.Exclude_shared_libs, props.Target.Apex.Exclude_shared_libs...),
963 props.Export_shared_lib_headers,
964 bazelLabelForSharedDepsExcludes,
965 )
Liz Kammere6583482021-10-19 13:56:10 -0400966 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
967 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Vinh Tran85fb07c2022-09-16 16:17:48 -0400968 la.resolveTargetApexProp(ctx, isBinary, props)
969
Wei Li81852ca2022-07-27 00:22:06 -0700970 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
971 // If a dependency in la.implementationDynamicDeps has stubs, its stub variant should be
972 // used when the dependency is linked in a APEX. The dependencies in NoConfigAxis and
973 // OsConfigurationAxis/OsAndroid are grouped by having stubs or not, so Bazel select()
974 // statement can be used to choose source/stub variants of them.
975 depsWithStubs := []bazel.Label{}
976 for _, l := range sharedDeps.implementation.Includes {
977 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
978 if m, ok := dep.(*Module); ok && m.HasStubsVariants() {
979 depsWithStubs = append(depsWithStubs, l)
980 }
981 }
982 if len(depsWithStubs) > 0 {
983 implDynamicDeps := bazel.SubtractBazelLabelList(sharedDeps.implementation, bazel.MakeLabelList(depsWithStubs))
984 la.implementationDynamicDeps.SetSelectValue(axis, config, implDynamicDeps)
985
986 stubLibLabels := []bazel.Label{}
987 for _, l := range depsWithStubs {
Liz Kammer91487d42022-09-13 11:27:11 -0400988 l.Label = l.Label + stubsSuffix
Wei Li81852ca2022-07-27 00:22:06 -0700989 stubLibLabels = append(stubLibLabels, l)
990 }
991 inApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex)
992 nonApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex)
993 defaultSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
994 if axis == bazel.NoConfigAxis {
995 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
996 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
997 (&defaultSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
Trevor Radcliffe0ed6b7d2022-09-12 20:19:26 +0000998 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
999 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
1000 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
Wei Li81852ca2022-07-27 00:22:06 -07001001 } else if config == bazel.OsAndroid {
1002 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
1003 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
Trevor Radcliffe0ed6b7d2022-09-12 20:19:26 +00001004 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1005 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
Wei Li81852ca2022-07-27 00:22:06 -07001006 }
1007 }
1008 }
Liz Kammere6583482021-10-19 13:56:10 -04001009
1010 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1011 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1012 }
1013
1014 if Bool(props.Allow_undefined_symbols) {
1015 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1016 }
1017
1018 var linkerFlags []string
1019 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001020 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001021 // binaries remove static flag if -shared is in the linker flags
1022 if isBinary && android.InList("-shared", linkerFlags) {
1023 axisFeatures = append(axisFeatures, "-static_flag")
1024 }
1025 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001026
1027 // This must happen before the addition of flags for Version Script and
1028 // Dynamic List, as these flags must be split on spaces and those must not
1029 linkerFlags = parseCommandLineFlags(linkerFlags, filterOutClangUnknownCflags)
1030
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001031 additionalLinkerInputs := bazel.LabelList{}
Liz Kammere6583482021-10-19 13:56:10 -04001032 if props.Version_script != nil {
1033 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001034 additionalLinkerInputs.Add(&label)
Liz Kammere6583482021-10-19 13:56:10 -04001035 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
1036 }
Alix773adaa2022-04-27 17:49:34 +00001037
1038 if props.Dynamic_list != nil {
1039 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001040 additionalLinkerInputs.Add(&label)
Alix773adaa2022-04-27 17:49:34 +00001041 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1042 }
1043
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001044 la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001045 la.linkopts.SetSelectValue(axis, config, linkerFlags)
Liz Kammere6583482021-10-19 13:56:10 -04001046 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
1047
1048 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
1049 if props.crt() != nil {
1050 if axis == bazel.NoConfigAxis {
1051 la.linkCrt.SetSelectValue(axis, config, props.crt())
1052 } else if axis == bazel.ArchConfigurationAxis {
1053 ctx.ModuleErrorf("nocrt is not supported for arch variants")
1054 }
1055 }
1056
1057 if axisFeatures != nil {
1058 la.features.SetSelectValue(axis, config, axisFeatures)
1059 }
Cole Faust6b29f592022-08-09 09:50:56 -07001060
1061 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1062 if !runtimeDeps.IsEmpty() {
1063 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1064 }
Liz Kammere6583482021-10-19 13:56:10 -04001065}
1066
Jingwen Chen55bc8202021-11-02 06:40:51 +00001067func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001068 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1069 if stripProperties, ok := props.(*StripProperties); ok {
1070 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1071 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1072 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1073 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1074 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001075 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001076 })
Liz Kammere6583482021-10-19 13:56:10 -04001077}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001078
Jingwen Chen55bc8202021-11-02 06:40:51 +00001079func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001080
Liz Kammer47535c52021-06-02 16:02:22 -04001081 type productVarDep struct {
1082 // the name of the corresponding excludes field, if one exists
1083 excludesField string
1084 // reference to the bazel attribute that should be set for the given product variable config
1085 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001086
Jingwen Chen55bc8202021-11-02 06:40:51 +00001087 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001088 }
1089
Zi Wang0a8a1292022-08-30 06:27:01 +00001090 // an intermediate attribute that holds Header_libs info, and will be appended to
1091 // implementationDeps at the end, to solve the confliction that both header_libs
1092 // and static_libs use implementationDeps.
1093 var headerDeps bazel.LabelListAttribute
1094
Liz Kammer47535c52021-06-02 16:02:22 -04001095 productVarToDepFields := map[string]productVarDep{
1096 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001097 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1098 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1099 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001100 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001101 }
1102
Liz Kammer47535c52021-06-02 16:02:22 -04001103 for name, dep := range productVarToDepFields {
1104 props, exists := productVariableProps[name]
1105 excludeProps, excludesExists := productVariableProps[dep.excludesField]
1106 // if neither an include or excludes property exists, then skip it
1107 if !exists && !excludesExists {
1108 continue
1109 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001110 // Collect all the configurations that an include or exclude property exists for.
1111 // We want to iterate all configurations rather than either the include or exclude because, for a
1112 // particular configuration, we may have either only an include or an exclude to handle.
1113 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
1114 for p := range props {
1115 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001116 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001117 for p := range excludeProps {
1118 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001119 }
1120
Jingwen Chen25825ca2021-11-15 12:28:43 +00001121 for productConfigProp := range productConfigProps {
1122 prop, includesExists := props[productConfigProp]
1123 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001124 var includes, excludes []string
1125 var ok bool
1126 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001127 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001128 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1129 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001130 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001131 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1132 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001133
Jingwen Chen58ff6802021-11-17 12:14:41 +00001134 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001135 dep.attribute.SetSelectValue(
1136 productConfigProp.ConfigurationAxis(),
1137 productConfigProp.SelectKey(),
1138 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1139 )
Liz Kammer47535c52021-06-02 16:02:22 -04001140 }
1141 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001142 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001143}
Liz Kammer47535c52021-06-02 16:02:22 -04001144
Liz Kammer54309532021-12-14 12:21:22 -05001145func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1146 // if system dynamic deps have the default value, any use of a system dynamic library used will
1147 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001148 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001149 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
1150 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001151 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001152 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1153 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001154 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001155 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1156 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001157
1158 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
1159 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, toRemove)
1160 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1161 for _, lib := range toRemove.Includes {
1162 lib.Label += stubsSuffix
1163 stubsToRemove = append(stubsToRemove, lib)
1164 }
1165 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001166 }
1167
Liz Kammere6583482021-10-19 13:56:10 -04001168 la.deps.ResolveExcludes()
1169 la.implementationDeps.ResolveExcludes()
1170 la.dynamicDeps.ResolveExcludes()
1171 la.implementationDynamicDeps.ResolveExcludes()
1172 la.wholeArchiveDeps.ResolveExcludes()
1173 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001174
Jingwen Chen91220d72021-03-24 02:18:33 -04001175}
1176
Jingwen Chened9c17d2021-04-13 07:14:55 +00001177// Relativize a list of root-relative paths with respect to the module's
1178// directory.
1179//
1180// include_dirs Soong prop are root-relative (b/183742505), but
1181// local_include_dirs, export_include_dirs and export_system_include_dirs are
1182// module dir relative. This function makes a list of paths entirely module dir
1183// relative.
1184//
1185// For the `include` attribute, Bazel wants the paths to be relative to the
1186// module.
1187func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001188 var relativePaths []string
1189 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001190 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1191 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1192 if err != nil {
1193 panic(err)
1194 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001195 relativePaths = append(relativePaths, relativePath)
1196 }
1197 return relativePaths
1198}
1199
Liz Kammer5fad5012021-09-09 14:08:21 -04001200// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1201// attributes.
1202type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001203 AbsoluteIncludes bazel.StringListAttribute
1204 Includes bazel.StringListAttribute
1205 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001206}
1207
Liz Kammer54549442022-05-11 13:55:06 -04001208func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001209 var exported BazelIncludes
1210 if includes != nil {
1211 exported = *includes
1212 } else {
1213 exported = BazelIncludes{}
1214 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001215 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1216 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1217 if len(flagExporterProperties.Export_include_dirs) > 0 {
1218 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1219 }
1220 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1221 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 -04001222 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001223 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001224 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001225 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001226 exported.Includes.DeduplicateAxesFromBase()
1227 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001228
Liz Kammer5fad5012021-09-09 14:08:21 -04001229 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001230}
Chris Parsons953b3562021-09-20 15:14:39 -04001231
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001232func BazelLabelNameForStaticModule(baseLabel string) string {
1233 return baseLabel + "_bp2build_cc_library_static"
1234}
1235
Jingwen Chen55bc8202021-11-02 06:40:51 +00001236func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001237 label := android.BazelModuleLabel(ctx, m)
Chris Parsonsad876012022-08-20 14:48:32 -04001238 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GetBp2BuildAllowList().GenerateCcLibraryStaticOnly(m.Name()) {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001239 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001240 }
1241 return label
1242}
1243
Jingwen Chen55bc8202021-11-02 06:40:51 +00001244func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001245 // cc_library, at it's root name, propagates the shared library, which depends on the static
1246 // library.
1247 return android.BazelModuleLabel(ctx, m)
1248}
1249
Jingwen Chen55bc8202021-11-02 06:40:51 +00001250func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001251 label := bazelLabelForStaticModule(ctx, m)
1252 if aModule, ok := m.(android.Module); ok {
1253 if android.IsModulePrebuilt(aModule) {
1254 label += "_alwayslink"
1255 }
1256 }
1257 return label
1258}
1259
Jingwen Chen55bc8202021-11-02 06:40:51 +00001260func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001261 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1262}
1263
Jingwen Chen55bc8202021-11-02 06:40:51 +00001264func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001265 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1266}
1267
Jingwen Chen55bc8202021-11-02 06:40:51 +00001268func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001269 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1270}
1271
Jingwen Chen55bc8202021-11-02 06:40:51 +00001272func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001273 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1274}
1275
Jingwen Chen55bc8202021-11-02 06:40:51 +00001276func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001277 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1278}
1279
Jingwen Chen55bc8202021-11-02 06:40:51 +00001280func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001281 // This is not elegant, but bp2build's shared library targets only propagate
1282 // their header information as part of the normal C++ provider.
1283 return bazelLabelForSharedDeps(ctx, modules)
1284}
1285
Zi Wang0a8a1292022-08-30 06:27:01 +00001286func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1287 // This is only used when product_variable header_libs is processed, to follow
1288 // the pattern of depResolutionFunc
1289 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1290}
1291
Jingwen Chen55bc8202021-11-02 06:40:51 +00001292func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001293 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1294}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001295
1296type binaryLinkerAttrs struct {
1297 Linkshared *bool
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001298 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001299}
1300
Jingwen Chen55bc8202021-11-02 06:40:51 +00001301func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001302 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001303 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1304 linkerProps := props.(*BinaryLinkerProperties)
1305 staticExecutable := linkerProps.Static_executable
1306 if axis == bazel.NoConfigAxis {
1307 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1308 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001309 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001310 } else if staticExecutable != nil {
1311 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1312 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1313 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001314 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001315 if suffix := linkerProps.Suffix; suffix != nil {
1316 attrs.Suffix.SetSelectValue(axis, config, suffix)
1317 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001318 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001319
1320 return attrs
1321}