blob: 972a8289599765b8d7ab3087c1482d9c3d9a82c2 [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) {
Alix1be00d42022-05-16 22:56:04 +0000177 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, true, 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
368func parseCommandLineFlags(soongFlags []string, noCoptsTokenization bool, 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.
Alix1be00d42022-05-16 22:56:04 +0000383 if noCoptsTokenization {
384 result = append(result, strings.Split(flag, " ")...)
385 } else {
386 // Soong's Version Script and Dynamic List Properties are added as flags
387 // to Bazel's linkopts using "($location label)" syntax.
388 // Splitting on spaces would separate this into two different flags
389 // "($ location" and "label)"
390 result = append(result, flag)
391 }
Liz Kammere6583482021-10-19 13:56:10 -0400392 }
393 return result
394}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000395
Jingwen Chen55bc8202021-11-02 06:40:51 +0000396func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400397 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
398 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
399 if srcsList, ok := parseSrcs(ctx, props); ok {
400 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400401 }
402
Liz Kammere6583482021-10-19 13:56:10 -0400403 localIncludeDirs := props.Local_include_dirs
404 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500405 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400406 if includeBuildDirectory(props.Include_build_directory) {
407 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400408 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000409 }
410
Liz Kammere6583482021-10-19 13:56:10 -0400411 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
412 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
413
Cole Faust5fa4e962022-08-22 14:31:04 -0700414 instructionSet := proptools.StringDefault(props.Instruction_set, "")
415 if instructionSet == "arm" {
416 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm", "-arm_isa_thumb"})
417 } else if instructionSet != "" && instructionSet != "thumb" {
418 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
419 }
420
Liz Kammercac7f692021-12-16 14:19:32 -0500421 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
422 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
423 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
424 // cases.
Alix1be00d42022-05-16 22:56:04 +0000425 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, true, filterOutStdFlag, filterOutClangUnknownCflags))
426 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, true, nil))
427 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, true, filterOutClangUnknownCflags))
428 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, true, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400429 ca.rtti.SetSelectValue(axis, config, props.Rtti)
430}
431
Jingwen Chen55bc8202021-11-02 06:40:51 +0000432func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000433 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
434 if stlProps, ok := props.(*StlProperties); ok {
435 if stlProps.Stl == nil {
436 return
437 }
438 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400439 stl := deduplicateStlInput(*stlProps.Stl)
440 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000441 } else if ca.stl != stlProps.Stl {
442 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 -0400443 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000444 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000445 })
Liz Kammere6583482021-10-19 13:56:10 -0400446}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000447
Jingwen Chen55bc8202021-11-02 06:40:51 +0000448func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400449 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400450 "Cflags": &ca.copts,
451 "Asflags": &ca.asFlags,
452 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400453 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400454 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000455 if productConfigProps, exists := productVariableProps[propName]; exists {
456 for productConfigProp, prop := range productConfigProps {
457 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400458 if !ok {
459 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
460 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000461 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
462 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400463 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400464 }
465 }
Liz Kammere6583482021-10-19 13:56:10 -0400466}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400467
Jingwen Chen55bc8202021-11-02 06:40:51 +0000468func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400469 ca.srcs.ResolveExcludes()
470 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
471
Liz Kammer12615db2021-09-28 09:19:17 -0400472 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400473 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400474
Liz Kammere6583482021-10-19 13:56:10 -0400475 for p, lla := range partitionedSrcs {
476 // if there are no sources, there is no need for headers
477 if lla.IsEmpty() {
478 continue
479 }
480 lla.Append(implementationHdrs)
481 partitionedSrcs[p] = lla
482 }
483
484 ca.srcs = partitionedSrcs[cppSrcPartition]
485 ca.cSrcs = partitionedSrcs[cSrcPartition]
486 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700487 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000488 ca.lSrcs = partitionedSrcs[lSrcPartition]
489 ca.llSrcs = partitionedSrcs[llSrcPartition]
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000490 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400491
492 ca.absoluteIncludes.DeduplicateAxesFromBase()
493 ca.localIncludes.DeduplicateAxesFromBase()
494}
495
496// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000497func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400498 anySrcs := false
499 // Add srcs-like dependencies such as generated files.
500 // First create a LabelList containing these dependencies, then merge the values with srcs.
501 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
502 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
503 anySrcs = true
504 }
505
506 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400507
Liz Kammere6583482021-10-19 13:56:10 -0400508 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
509 anySrcs = true
510 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400511
Liz Kammere6583482021-10-19 13:56:10 -0400512 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
513}
514
Liz Kammera5a29de2022-05-25 23:19:37 -0400515func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
516 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500517 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
518 // Defaults are handled by the toolchain definition.
519 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400520 stdVal := proptools.StringDefault(std, defaultVal)
521 if stdVal == "experimental" || stdVal == defaultVal {
522 if stdVal == "experimental" {
523 stdVal = prefix + "_std_experimental"
524 }
525 if !useGnu {
526 stdVal += "_no_gnu"
527 }
528 } else if !useGnu {
529 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500530 }
531
Liz Kammera5a29de2022-05-25 23:19:37 -0400532 if stdVal == defaultVal {
533 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500534 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400535 return &stdVal
536}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500537
Liz Kammera5a29de2022-05-25 23:19:37 -0400538func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
539 useGnu := useGnuExtensions(gnu_extensions)
540
541 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400542}
543
Liz Kammer1263d9b2021-12-10 14:28:20 -0500544// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
545// is fully-qualified.
546// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
547func packageFromLabel(label string) (string, bool) {
548 split := strings.Split(label, ":")
549 if len(split) != 2 {
550 return "", false
551 }
552 if split[0] == "" {
553 return ".", false
554 }
555 // remove leading "//"
556 return split[0][2:], true
557}
558
559// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
560func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
561 for _, hdr := range labelList.Includes {
562 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
563 absolute = append(absolute, pkg)
564 } else if pkg != "" {
565 relative = append(relative, pkg)
566 }
567 }
568 return relative, absolute
569}
570
Cole Faust7071a052022-07-29 15:58:33 -0700571type YasmAttributes struct {
572 Srcs bazel.LabelListAttribute
573 Flags bazel.StringListAttribute
574 Include_dirs bazel.StringListAttribute
575}
576
577func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
578 if ca.asmSrcs.IsEmpty() {
579 return nil
580 }
581
582 // Yasm needs the include directories from both local_includes and
583 // export_include_dirs. We don't care about actually exporting them from the
584 // yasm rule though, because they will also be present on the cc_ rule that
585 // wraps this yasm rule.
586 includes := ca.localIncludes.Clone()
587 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
588 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
589 if len(flagExporterProperties.Export_include_dirs) > 0 {
590 x := bazel.StringListAttribute{}
591 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
592 includes.Append(x)
593 }
594 }
595 })
596
597 ctx.CreateBazelTargetModule(
598 bazel.BazelTargetModuleProperties{
599 Rule_class: "yasm",
600 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
601 },
602 android.CommonAttributes{Name: m.Name() + "_yasm"},
603 &YasmAttributes{
604 Srcs: ca.asmSrcs,
605 Flags: ca.asFlags,
606 Include_dirs: *includes,
607 })
608
609 // We only want to add a dependency on the _yasm target if there are asm
610 // sources in the current configuration. If there are unconfigured asm
611 // sources, always add the dependency. Otherwise, add the dependency only
612 // on the configuration axes and values that had asm sources.
613 if len(ca.asmSrcs.Value.Includes) > 0 {
614 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
615 }
616
617 ret := &bazel.LabelAttribute{}
618 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
619 for config := range ca.asmSrcs.ConfigurableValues[axis] {
620 ret.SetSelectValue(axis, config, bazel.Label{Label: ":" + m.Name() + "_yasm"})
621 }
622 }
623 return ret
624}
625
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000626// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400627func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400628 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
629 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000630 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400631
632 var implementationHdrs bazel.LabelListAttribute
633
634 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
635 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
636 for axis, configMap := range cp {
637 if _, ok := axisToConfigs[axis]; !ok {
638 axisToConfigs[axis] = map[string]bool{}
639 }
640 for config, _ := range configMap {
641 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400642 }
643 }
644 }
Liz Kammere6583482021-10-19 13:56:10 -0400645 allAxesAndConfigs(archVariantCompilerProps)
646 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000647 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400648
Liz Kammere6583482021-10-19 13:56:10 -0400649 compilerAttrs := compilerAttributes{}
650 linkerAttrs := linkerAttributes{}
651
652 for axis, configs := range axisToConfigs {
653 for config, _ := range configs {
654 var allHdrs []string
655 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
656 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000657 if baseCompilerProps.Lex != nil {
658 compilerAttrs.lexopts.SetSelectValue(axis, config, baseCompilerProps.Lex.Flags)
659 }
Liz Kammere6583482021-10-19 13:56:10 -0400660 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
661 }
662
663 var exportHdrs []string
664
665 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
666 exportHdrs = baseLinkerProps.Export_generated_headers
667
668 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
669 }
670 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
671 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
672 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500673
674 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
675 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
676 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
677
678 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
679 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
680 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400681
Liz Kammer1263d9b2021-12-10 14:28:20 -0500682 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400683
Liz Kammer1263d9b2021-12-10 14:28:20 -0500684 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
685 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400686
Liz Kammer1263d9b2021-12-10 14:28:20 -0500687 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000688
689 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
690 if axis == bazel.NoConfigAxis {
691 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
692 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
693 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500694 if suffix := libraryProps.Suffix; suffix != nil {
695 compilerAttrs.suffix.SetSelectValue(axis, config, suffix)
696 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000697 }
Liz Kammere6583482021-10-19 13:56:10 -0400698 }
699 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400700
Liz Kammere6583482021-10-19 13:56:10 -0400701 compilerAttrs.convertStlProps(ctx, module)
702 (&linkerAttrs).convertStripProps(ctx, module)
703
Yu Liu8d82ac52022-05-17 15:13:28 -0700704 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
705 !Bool(module.coverage.Properties.Native_coverage) {
706 // Native_coverage is arch neutral
707 (&linkerAttrs).features.Append(bazel.MakeStringListAttribute([]string{"-coverage"}))
708 }
709
Liz Kammere6583482021-10-19 13:56:10 -0400710 productVariableProps := android.ProductVariableProperties(ctx)
711
712 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
713 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
714
715 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500716 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400717
Cole Faust7071a052022-07-29 15:58:33 -0700718 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
719
Liz Kammer12615db2021-09-28 09:19:17 -0400720 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
721
722 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
723 // which. This will add the newly generated proto library to the appropriate attribute and nothing
724 // to the other
725 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
726 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400727
728 aidlDep := bp2buildCcAidlLibrary(ctx, module, compilerAttrs.aidlSrcs)
729 if aidlDep != nil {
730 if lib, ok := module.linker.(*libraryDecorator); ok {
731 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
732 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
733 } else {
734 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
735 }
736 }
737 }
Liz Kammer12615db2021-09-28 09:19:17 -0400738
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000739 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
740 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
741 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
742
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000743 if !compilerAttrs.syspropSrcs.IsEmpty() {
744 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
745 }
746
Cole Faust5fa4e962022-08-22 14:31:04 -0700747 features := compilerAttrs.features.Clone().Append(linkerAttrs.features)
748 features.DeduplicateAxesFromBase()
749
Liz Kammere6583482021-10-19 13:56:10 -0400750 return baseAttributes{
751 compilerAttrs,
752 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700753 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400754 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400755 aidlDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000756 }
757}
758
Vinh Tran9f6796a2022-08-16 13:10:31 -0400759func bp2buildCcAidlLibrary(
760 ctx android.Bp2buildMutatorContext,
761 m *Module,
Vinh Trana3b8b782022-09-14 11:40:24 -0400762 aidlLabelList bazel.LabelListAttribute,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400763) *bazel.LabelAttribute {
Vinh Trana3b8b782022-09-14 11:40:24 -0400764 if !aidlLabelList.IsEmpty() {
765 aidlLibs, aidlSrcs := aidlLabelList.Partition(func(src bazel.Label) bool {
766 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
767 fg.ShouldConvertToAidlLibrary(ctx) {
768 return true
769 }
770 return false
771 })
Vinh Tran9f6796a2022-08-16 13:10:31 -0400772
Vinh Trana3b8b782022-09-14 11:40:24 -0400773 if !aidlSrcs.IsEmpty() {
774 aidlLibName := m.Name() + "_aidl_library"
775 ctx.CreateBazelTargetModule(
776 bazel.BazelTargetModuleProperties{
777 Rule_class: "aidl_library",
778 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
779 },
780 android.CommonAttributes{Name: aidlLibName},
781 &aidlLibraryAttributes{
782 Srcs: aidlSrcs,
783 },
784 )
785 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
786 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400787
Vinh Trana3b8b782022-09-14 11:40:24 -0400788 if !aidlLibs.IsEmpty() {
789 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
790 ctx.CreateBazelTargetModule(
791 bazel.BazelTargetModuleProperties{
792 Rule_class: "cc_aidl_library",
793 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
794 },
795 android.CommonAttributes{Name: ccAidlLibrarylabel},
796 &ccAidlLibraryAttributes{
797 Deps: aidlLibs,
798 },
799 )
800 label := &bazel.LabelAttribute{
801 Value: &bazel.Label{
802 Label: ":" + ccAidlLibrarylabel,
803 },
804 }
805 return label
806 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400807 }
808
Vinh Trana3b8b782022-09-14 11:40:24 -0400809 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -0400810}
811
Yu Liufc603162022-03-01 15:44:08 -0800812func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000813 return sdkAttributes{
814 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800815 Min_sdk_version: module.Properties.Min_sdk_version,
816 }
817}
818
819type sdkAttributes struct {
820 Sdk_version *string
821 Min_sdk_version *string
822}
823
Jingwen Chen107c0de2021-04-09 10:43:12 +0000824// Convenience struct to hold all attributes parsed from linker properties.
825type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500826 deps bazel.LabelListAttribute
827 implementationDeps bazel.LabelListAttribute
828 dynamicDeps bazel.LabelListAttribute
829 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -0700830 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -0500831 wholeArchiveDeps bazel.LabelListAttribute
832 implementationWholeArchiveDeps bazel.LabelListAttribute
833 systemDynamicDeps bazel.LabelListAttribute
834 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400835
Jingwen Chen6ada5892021-09-17 11:38:09 +0000836 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000837 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500838 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000839 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400840 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000841 stripKeepSymbols bazel.BoolAttribute
842 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
843 stripKeepSymbolsList bazel.StringListAttribute
844 stripAll bazel.BoolAttribute
845 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400846 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400847}
848
Liz Kammer54309532021-12-14 12:21:22 -0500849var (
850 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -0400851 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -0500852)
853
Vinh Tran85fb07c2022-09-16 16:17:48 -0400854// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
855// since all libs are already excluded by default
856func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, isBinary bool, props *BaseLinkerProperties) {
857 sharedLibsForNonApex := maybePartitionExportedAndImplementationsDeps(
858 ctx,
859 true,
860 props.Target.Apex.Exclude_shared_libs,
861 props.Export_shared_lib_headers,
862 bazelLabelForSharedDeps,
863 )
864 dynamicDeps := la.dynamicDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
865 implDynamicDeps := la.implementationDynamicDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
866 (&dynamicDeps).Append(sharedLibsForNonApex.export)
867 (&implDynamicDeps).Append(sharedLibsForNonApex.implementation)
868 la.dynamicDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, dynamicDeps)
869 la.implementationDynamicDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, implDynamicDeps)
870
871 staticLibsForNonApex := maybePartitionExportedAndImplementationsDeps(
872 ctx,
873 !isBinary,
874 props.Target.Apex.Exclude_static_libs,
875 props.Export_static_lib_headers,
876 bazelLabelForSharedDeps,
877 )
878 deps := la.deps.SelectValue(bazel.InApexAxis, bazel.NonApex)
879 implDeps := la.implementationDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
880 (&deps).Append(staticLibsForNonApex.export)
881 (&implDeps).Append(staticLibsForNonApex.implementation)
882 la.deps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, deps)
883 la.implementationDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, implDeps)
884}
885
Jingwen Chen55bc8202021-11-02 06:40:51 +0000886func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400887 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
888 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400889
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400890 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -0400891 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
892 if axis == bazel.NoConfigAxis {
893 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
894 if proptools.Bool(props.Use_version_lib) {
895 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
896 // remove from static libs so there is no duplicate dependency
897 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
898 // only add the dep if it is not in progress
899 if !versionLibAlreadyInDeps {
900 if isBinary {
901 wholeStaticLibs = append(wholeStaticLibs, versionLib)
902 } else {
903 la.implementationWholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, []string{versionLib}, props.Exclude_static_libs))
904 }
905 }
906 }
907 }
908
Liz Kammere6583482021-10-19 13:56:10 -0400909 // Excludes to parallel Soong:
910 // 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 -0400911 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400912
Vinh Tran85fb07c2022-09-16 16:17:48 -0400913 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
914 ctx,
915 !isBinary,
916 staticLibs,
917 // Exclude static libs in Exclude_static_libs and Target.Apex.Exclude_static_libs props
918 append(props.Exclude_static_libs, props.Target.Apex.Exclude_static_libs...),
919 props.Export_static_lib_headers,
920 bazelLabelForStaticDepsExcludes,
921 )
Liz Kammer7a210ac2021-09-22 15:52:58 -0400922
Liz Kammere6583482021-10-19 13:56:10 -0400923 headerLibs := android.FirstUniqueStrings(props.Header_libs)
924 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400925
Liz Kammere6583482021-10-19 13:56:10 -0400926 (&hDeps.export).Append(staticDeps.export)
927 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000928
Liz Kammere6583482021-10-19 13:56:10 -0400929 (&hDeps.implementation).Append(staticDeps.implementation)
930 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400931
Liz Kammere6583482021-10-19 13:56:10 -0400932 systemSharedLibs := props.System_shared_libs
933 // systemSharedLibs distinguishes between nil/empty list behavior:
934 // nil -> use default values
935 // empty list -> no values specified
936 if len(systemSharedLibs) > 0 {
937 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
938 }
939 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
940
941 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500942 excludeSharedLibs := props.Exclude_shared_libs
943 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
944 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
945 })
946 for _, el := range usedSystem {
947 if la.usedSystemDynamicDepAsDynamicDep == nil {
948 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
949 }
950 la.usedSystemDynamicDepAsDynamicDep[el] = true
951 }
952
Vinh Tran85fb07c2022-09-16 16:17:48 -0400953 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
954 ctx,
955 !isBinary,
956 sharedLibs,
957 // Exclude shared libs in Exclude_shared_libs and Target.Apex.Exclude_shared_libs props
958 append(props.Exclude_shared_libs, props.Target.Apex.Exclude_shared_libs...),
959 props.Export_shared_lib_headers,
960 bazelLabelForSharedDepsExcludes,
961 )
Liz Kammere6583482021-10-19 13:56:10 -0400962 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
963 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Vinh Tran85fb07c2022-09-16 16:17:48 -0400964 la.resolveTargetApexProp(ctx, isBinary, props)
965
Wei Li81852ca2022-07-27 00:22:06 -0700966 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
967 // If a dependency in la.implementationDynamicDeps has stubs, its stub variant should be
968 // used when the dependency is linked in a APEX. The dependencies in NoConfigAxis and
969 // OsConfigurationAxis/OsAndroid are grouped by having stubs or not, so Bazel select()
970 // statement can be used to choose source/stub variants of them.
971 depsWithStubs := []bazel.Label{}
972 for _, l := range sharedDeps.implementation.Includes {
973 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
974 if m, ok := dep.(*Module); ok && m.HasStubsVariants() {
975 depsWithStubs = append(depsWithStubs, l)
976 }
977 }
978 if len(depsWithStubs) > 0 {
979 implDynamicDeps := bazel.SubtractBazelLabelList(sharedDeps.implementation, bazel.MakeLabelList(depsWithStubs))
980 la.implementationDynamicDeps.SetSelectValue(axis, config, implDynamicDeps)
981
982 stubLibLabels := []bazel.Label{}
983 for _, l := range depsWithStubs {
Liz Kammer91487d42022-09-13 11:27:11 -0400984 l.Label = l.Label + stubsSuffix
Wei Li81852ca2022-07-27 00:22:06 -0700985 stubLibLabels = append(stubLibLabels, l)
986 }
987 inApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex)
988 nonApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex)
989 defaultSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
990 if axis == bazel.NoConfigAxis {
991 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
992 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
993 (&defaultSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
Trevor Radcliffe0ed6b7d2022-09-12 20:19:26 +0000994 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
995 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
996 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
Wei Li81852ca2022-07-27 00:22:06 -0700997 } else if config == bazel.OsAndroid {
998 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
999 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
Trevor Radcliffe0ed6b7d2022-09-12 20:19:26 +00001000 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1001 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
Wei Li81852ca2022-07-27 00:22:06 -07001002 }
1003 }
1004 }
Liz Kammere6583482021-10-19 13:56:10 -04001005
1006 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1007 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1008 }
1009
1010 if Bool(props.Allow_undefined_symbols) {
1011 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1012 }
1013
1014 var linkerFlags []string
1015 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001016 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001017 // binaries remove static flag if -shared is in the linker flags
1018 if isBinary && android.InList("-shared", linkerFlags) {
1019 axisFeatures = append(axisFeatures, "-static_flag")
1020 }
1021 }
1022 if props.Version_script != nil {
1023 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
1024 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
1025 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
1026 }
Alix773adaa2022-04-27 17:49:34 +00001027
1028 if props.Dynamic_list != nil {
1029 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
1030 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
1031 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1032 }
1033
Alix1be00d42022-05-16 22:56:04 +00001034 la.linkopts.SetSelectValue(axis, config, parseCommandLineFlags(linkerFlags, false, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -04001035 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
1036
1037 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
1038 if props.crt() != nil {
1039 if axis == bazel.NoConfigAxis {
1040 la.linkCrt.SetSelectValue(axis, config, props.crt())
1041 } else if axis == bazel.ArchConfigurationAxis {
1042 ctx.ModuleErrorf("nocrt is not supported for arch variants")
1043 }
1044 }
1045
1046 if axisFeatures != nil {
1047 la.features.SetSelectValue(axis, config, axisFeatures)
1048 }
Cole Faust6b29f592022-08-09 09:50:56 -07001049
1050 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1051 if !runtimeDeps.IsEmpty() {
1052 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1053 }
Liz Kammere6583482021-10-19 13:56:10 -04001054}
1055
Jingwen Chen55bc8202021-11-02 06:40:51 +00001056func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001057 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1058 if stripProperties, ok := props.(*StripProperties); ok {
1059 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1060 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1061 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1062 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1063 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001064 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001065 })
Liz Kammere6583482021-10-19 13:56:10 -04001066}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001067
Jingwen Chen55bc8202021-11-02 06:40:51 +00001068func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001069
Liz Kammer47535c52021-06-02 16:02:22 -04001070 type productVarDep struct {
1071 // the name of the corresponding excludes field, if one exists
1072 excludesField string
1073 // reference to the bazel attribute that should be set for the given product variable config
1074 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001075
Jingwen Chen55bc8202021-11-02 06:40:51 +00001076 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001077 }
1078
Zi Wang0a8a1292022-08-30 06:27:01 +00001079 // an intermediate attribute that holds Header_libs info, and will be appended to
1080 // implementationDeps at the end, to solve the confliction that both header_libs
1081 // and static_libs use implementationDeps.
1082 var headerDeps bazel.LabelListAttribute
1083
Liz Kammer47535c52021-06-02 16:02:22 -04001084 productVarToDepFields := map[string]productVarDep{
1085 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001086 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1087 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1088 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001089 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001090 }
1091
Liz Kammer47535c52021-06-02 16:02:22 -04001092 for name, dep := range productVarToDepFields {
1093 props, exists := productVariableProps[name]
1094 excludeProps, excludesExists := productVariableProps[dep.excludesField]
1095 // if neither an include or excludes property exists, then skip it
1096 if !exists && !excludesExists {
1097 continue
1098 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001099 // Collect all the configurations that an include or exclude property exists for.
1100 // We want to iterate all configurations rather than either the include or exclude because, for a
1101 // particular configuration, we may have either only an include or an exclude to handle.
1102 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
1103 for p := range props {
1104 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001105 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001106 for p := range excludeProps {
1107 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001108 }
1109
Jingwen Chen25825ca2021-11-15 12:28:43 +00001110 for productConfigProp := range productConfigProps {
1111 prop, includesExists := props[productConfigProp]
1112 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001113 var includes, excludes []string
1114 var ok bool
1115 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001116 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001117 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1118 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001119 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001120 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1121 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001122
Jingwen Chen58ff6802021-11-17 12:14:41 +00001123 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001124 dep.attribute.SetSelectValue(
1125 productConfigProp.ConfigurationAxis(),
1126 productConfigProp.SelectKey(),
1127 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1128 )
Liz Kammer47535c52021-06-02 16:02:22 -04001129 }
1130 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001131 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001132}
Liz Kammer47535c52021-06-02 16:02:22 -04001133
Liz Kammer54309532021-12-14 12:21:22 -05001134func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1135 // if system dynamic deps have the default value, any use of a system dynamic library used will
1136 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001137 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001138 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
1139 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001140 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001141 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1142 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001143 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001144 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1145 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001146
1147 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
1148 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, toRemove)
1149 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1150 for _, lib := range toRemove.Includes {
1151 lib.Label += stubsSuffix
1152 stubsToRemove = append(stubsToRemove, lib)
1153 }
1154 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001155 }
1156
Liz Kammere6583482021-10-19 13:56:10 -04001157 la.deps.ResolveExcludes()
1158 la.implementationDeps.ResolveExcludes()
1159 la.dynamicDeps.ResolveExcludes()
1160 la.implementationDynamicDeps.ResolveExcludes()
1161 la.wholeArchiveDeps.ResolveExcludes()
1162 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001163
Jingwen Chen91220d72021-03-24 02:18:33 -04001164}
1165
Jingwen Chened9c17d2021-04-13 07:14:55 +00001166// Relativize a list of root-relative paths with respect to the module's
1167// directory.
1168//
1169// include_dirs Soong prop are root-relative (b/183742505), but
1170// local_include_dirs, export_include_dirs and export_system_include_dirs are
1171// module dir relative. This function makes a list of paths entirely module dir
1172// relative.
1173//
1174// For the `include` attribute, Bazel wants the paths to be relative to the
1175// module.
1176func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001177 var relativePaths []string
1178 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001179 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1180 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1181 if err != nil {
1182 panic(err)
1183 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001184 relativePaths = append(relativePaths, relativePath)
1185 }
1186 return relativePaths
1187}
1188
Liz Kammer5fad5012021-09-09 14:08:21 -04001189// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1190// attributes.
1191type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001192 AbsoluteIncludes bazel.StringListAttribute
1193 Includes bazel.StringListAttribute
1194 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001195}
1196
Liz Kammer54549442022-05-11 13:55:06 -04001197func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001198 var exported BazelIncludes
1199 if includes != nil {
1200 exported = *includes
1201 } else {
1202 exported = BazelIncludes{}
1203 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001204 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1205 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1206 if len(flagExporterProperties.Export_include_dirs) > 0 {
1207 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1208 }
1209 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1210 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 -04001211 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001212 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001213 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001214 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001215 exported.Includes.DeduplicateAxesFromBase()
1216 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001217
Liz Kammer5fad5012021-09-09 14:08:21 -04001218 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001219}
Chris Parsons953b3562021-09-20 15:14:39 -04001220
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001221func BazelLabelNameForStaticModule(baseLabel string) string {
1222 return baseLabel + "_bp2build_cc_library_static"
1223}
1224
Jingwen Chen55bc8202021-11-02 06:40:51 +00001225func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001226 label := android.BazelModuleLabel(ctx, m)
Chris Parsonsad876012022-08-20 14:48:32 -04001227 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GetBp2BuildAllowList().GenerateCcLibraryStaticOnly(m.Name()) {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001228 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001229 }
1230 return label
1231}
1232
Jingwen Chen55bc8202021-11-02 06:40:51 +00001233func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001234 // cc_library, at it's root name, propagates the shared library, which depends on the static
1235 // library.
1236 return android.BazelModuleLabel(ctx, m)
1237}
1238
Jingwen Chen55bc8202021-11-02 06:40:51 +00001239func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001240 label := bazelLabelForStaticModule(ctx, m)
1241 if aModule, ok := m.(android.Module); ok {
1242 if android.IsModulePrebuilt(aModule) {
1243 label += "_alwayslink"
1244 }
1245 }
1246 return label
1247}
1248
Jingwen Chen55bc8202021-11-02 06:40:51 +00001249func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001250 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1251}
1252
Jingwen Chen55bc8202021-11-02 06:40:51 +00001253func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001254 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1255}
1256
Jingwen Chen55bc8202021-11-02 06:40:51 +00001257func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001258 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1259}
1260
Jingwen Chen55bc8202021-11-02 06:40:51 +00001261func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001262 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1263}
1264
Jingwen Chen55bc8202021-11-02 06:40:51 +00001265func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001266 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1267}
1268
Jingwen Chen55bc8202021-11-02 06:40:51 +00001269func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001270 // This is not elegant, but bp2build's shared library targets only propagate
1271 // their header information as part of the normal C++ provider.
1272 return bazelLabelForSharedDeps(ctx, modules)
1273}
1274
Zi Wang0a8a1292022-08-30 06:27:01 +00001275func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1276 // This is only used when product_variable header_libs is processed, to follow
1277 // the pattern of depResolutionFunc
1278 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1279}
1280
Jingwen Chen55bc8202021-11-02 06:40:51 +00001281func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001282 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1283}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001284
1285type binaryLinkerAttrs struct {
1286 Linkshared *bool
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001287 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001288}
1289
Jingwen Chen55bc8202021-11-02 06:40:51 +00001290func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001291 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001292 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1293 linkerProps := props.(*BinaryLinkerProperties)
1294 staticExecutable := linkerProps.Static_executable
1295 if axis == bazel.NoConfigAxis {
1296 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1297 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001298 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001299 } else if staticExecutable != nil {
1300 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1301 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1302 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001303 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001304 if suffix := linkerProps.Suffix; suffix != nil {
1305 attrs.Suffix.SetSelectValue(axis, config, suffix)
1306 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001307 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001308
1309 return attrs
1310}