blob: ca2a6ee9b48417c623cb92003ebada8c834dfec2 [file] [log] [blame]
Jingwen Chen91220d72021-03-24 02:18:33 -04001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
Cole Faust7071a052022-07-29 15:58:33 -07007// http://www.apache.org/licenses/LICENSE-2.0
Jingwen Chen91220d72021-03-24 02:18:33 -04008//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14package cc
15
16import (
Liz Kammerd2871182021-10-04 13:54:37 -040017 "fmt"
Jingwen Chened9c17d2021-04-13 07:14:55 +000018 "path/filepath"
Jingwen Chen3950cd62021-05-12 04:33:00 +000019 "strings"
Chris Parsons484e50a2021-05-13 15:13:04 -040020
21 "android/soong/android"
22 "android/soong/bazel"
Alix1be00d42022-05-16 22:56:04 +000023 "android/soong/cc/config"
Liz Kammer7a210ac2021-09-22 15:52:58 -040024
Chris Parsons953b3562021-09-20 15:14:39 -040025 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040026
27 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040028)
29
Liz Kammerae3994e2021-10-19 09:45:48 -040030const (
Liz Kammer12615db2021-09-28 09:19:17 -040031 cSrcPartition = "c"
32 asSrcPartition = "as"
Cole Faust7071a052022-07-29 15:58:33 -070033 asmSrcPartition = "asm"
Trevor Radcliffeef9c9002022-05-13 20:55:35 +000034 lSrcPartition = "l"
35 llSrcPartition = "ll"
Liz Kammer12615db2021-09-28 09:19:17 -040036 cppSrcPartition = "cpp"
37 protoSrcPartition = "proto"
Vinh Tran9f6796a2022-08-16 13:10:31 -040038 aidlSrcPartition = "aidl"
Liz Kammer91487d42022-09-13 11:27:11 -040039
40 stubsSuffix = "_stub_libs_current"
Liz Kammerae3994e2021-10-19 09:45:48 -040041)
42
Liz Kammer2222c6b2021-05-24 15:41:47 -040043// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000044// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040045type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040046 Srcs bazel.LabelListAttribute
47 Srcs_c bazel.LabelListAttribute
48 Srcs_as bazel.LabelListAttribute
49 Srcs_aidl bazel.LabelListAttribute
50 Hdrs bazel.LabelListAttribute
51 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000052
Liz Kammer12615db2021-09-28 09:19:17 -040053 Deps bazel.LabelListAttribute
54 Implementation_deps bazel.LabelListAttribute
55 Dynamic_deps bazel.LabelListAttribute
56 Implementation_dynamic_deps bazel.LabelListAttribute
57 Whole_archive_deps bazel.LabelListAttribute
58 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070059 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040060
61 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050062
63 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080064
Yu Liu8d82ac52022-05-17 15:13:28 -070065 Native_coverage bazel.BoolAttribute
66
Yu Liufc603162022-03-01 15:44:08 -080067 sdkAttributes
Jingwen Chen53681ef2021-04-29 08:15:13 +000068}
69
Sam Delmericoc7681022022-02-04 21:01:20 +000070// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +000071func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -040072 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
73 // macro.
74 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -040075 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
76
77 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -040078 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -040079 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
80 return labelStr, false
81 }
Yu Liu2aa806b2022-09-01 11:54:47 -070082 // If the filegroup is already converted to aidl_library or proto_library,
83 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
84 fg, _ := m.(android.FileGroupAsLibrary)
85 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -040086 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000087 }
Liz Kammer12615db2021-09-28 09:19:17 -040088 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040089 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000090 }
91
Liz Kammer57e2e7a2021-09-20 12:55:02 -040092 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +000093 labels := bazel.LabelPartitions{
94 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -050095 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
96 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -070097 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -040098 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +000099 // TODO(http://b/231968910): If there is ever a filegroup target that
100 // contains .l or .ll files we will need to find a way to add a
101 // LabelMapper for these that identifies these filegroups and
102 // converts them appropriately
103 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
104 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400105 // C++ is the "catch-all" group, and comprises generated sources because we don't
106 // know the language of these sources until the genrule is executed.
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500107 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
Sam Delmericoc7681022022-02-04 21:01:20 +0000108 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000109
Sam Delmericoc7681022022-02-04 21:01:20 +0000110 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000111}
112
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000113// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000114func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000115 lib, ok := module.compiler.(*libraryDecorator)
116 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400117 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000118 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000119 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
120}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000121
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000122// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000123func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000124 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000125}
126
127// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000128func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000129 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400130}
131
Liz Kammer7a210ac2021-09-22 15:52:58 -0400132type depsPartition struct {
133 export bazel.LabelList
134 implementation bazel.LabelList
135}
136
Jingwen Chen55bc8202021-11-02 06:40:51 +0000137type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400138
Jingwen Chen55bc8202021-11-02 06:40:51 +0000139func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400140 if !exportsDeps {
141 return depsPartition{
142 implementation: fn(ctx, allDeps),
143 }
144 }
145
Liz Kammer7a210ac2021-09-22 15:52:58 -0400146 implementation, export := android.FilterList(allDeps, exportedDeps)
147
148 return depsPartition{
149 export: fn(ctx, export),
150 implementation: fn(ctx, implementation),
151 }
152}
153
Jingwen Chen55bc8202021-11-02 06:40:51 +0000154type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400155
Jingwen Chen55bc8202021-11-02 06:40:51 +0000156func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400157 if !exportsDeps {
158 return depsPartition{
159 implementation: fn(ctx, allDeps, excludes),
160 }
161 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400162 implementation, export := android.FilterList(allDeps, exportedDeps)
163
164 return depsPartition{
165 export: fn(ctx, export, excludes),
166 implementation: fn(ctx, implementation, excludes),
167 }
168}
169
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000170// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000171func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400172 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000173
Liz Kammer9abd62d2021-05-21 08:37:59 -0400174 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Alix1be00d42022-05-16 22:56:04 +0000175 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, true, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000176 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400177 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400178
Liz Kammer2b8004b2021-10-04 13:55:44 -0400179 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400180 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
181 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
182
Liz Kammer2b8004b2021-10-04 13:55:44 -0400183 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400184 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
185 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
186
187 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500188 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000189 }
Liz Kammer135bf552021-08-11 10:46:06 -0400190 // system_dynamic_deps distinguishes between nil/empty list behavior:
191 // nil -> use default values
192 // empty list -> no values specified
193 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000194
195 if isStatic {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000196 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
197 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
198 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000199 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000200 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000201 } else {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000202 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
203 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
204 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000205 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000206 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000207 }
208
Liz Kammerae3994e2021-10-19 09:45:48 -0400209 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
210 attrs.Srcs = partitionedSrcs[cppSrcPartition]
211 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
212 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000213
Liz Kammer12615db2021-09-28 09:19:17 -0400214 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
215 // TODO(b/208815215): determine whether this is used and add support if necessary
216 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
217 }
218
Jingwen Chenbcf53042021-05-26 04:42:42 +0000219 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000220}
221
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400222// Convenience struct to hold all attributes parsed from prebuilt properties.
223type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000224 Src bazel.LabelAttribute
225 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400226}
227
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000228// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000229func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) prebuiltAttributes {
230 manySourceFileError := func(axis bazel.ConfigurationAxis, config string) {
231 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most one source file for %s %s\n", axis, config)
232 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400233 var srcLabelAttribute bazel.LabelAttribute
234
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000235 parseSrcs := func(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, srcs []string) {
236 if len(srcs) > 1 {
237 manySourceFileError(axis, config)
238 return
239 } else if len(srcs) == 0 {
240 return
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400241 }
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000242 if srcLabelAttribute.SelectValue(axis, config) != nil {
243 manySourceFileError(axis, config)
244 return
245 }
246
247 src := android.BazelLabelForModuleSrcSingle(ctx, srcs[0])
248 srcLabelAttribute.SetSelectValue(axis, config, src)
249 }
250
251 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
252 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
253 parseSrcs(ctx, axis, config, prebuiltLinkerProperties.Srcs)
254 }
255 })
256
257 var enabledLabelAttribute bazel.BoolAttribute
258 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
259 if props.Enabled != nil {
260 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
261 }
262 parseSrcs(ctx, axis, config, props.Srcs)
263 }
264
265 if isStatic {
266 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
267 if staticProperties, ok := props.(*StaticProperties); ok {
268 parseAttrs(axis, config, staticProperties.Static)
269 }
270 })
271 } else {
272 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
273 if sharedProperties, ok := props.(*SharedProperties); ok {
274 parseAttrs(axis, config, sharedProperties.Shared)
275 }
276 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400277 }
278
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400279 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000280 Src: srcLabelAttribute,
281 Enabled: enabledLabelAttribute,
282 }
283}
284
285func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
286 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
287 for config, props := range configToProps {
288 parseFunc(axis, config, props)
289 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400290 }
291}
292
Liz Kammere6583482021-10-19 13:56:10 -0400293type baseAttributes struct {
294 compilerAttributes
295 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400296
Cole Faust5fa4e962022-08-22 14:31:04 -0700297 // A combination of compilerAttributes.features and linkerAttributes.features
298 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400299 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400300 aidlDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400301}
302
Jingwen Chen107c0de2021-04-09 10:43:12 +0000303// Convenience struct to hold all attributes parsed from compiler properties.
304type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400305 // Options for all languages
306 copts bazel.StringListAttribute
307 // Assembly options and sources
308 asFlags bazel.StringListAttribute
309 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700310 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400311 // C options and sources
312 conlyFlags bazel.StringListAttribute
313 cSrcs bazel.LabelListAttribute
314 // C++ options and sources
315 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000316 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400317
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000318 // Lex sources and options
319 lSrcs bazel.LabelListAttribute
320 llSrcs bazel.LabelListAttribute
321 lexopts bazel.StringListAttribute
322
Liz Kammere6583482021-10-19 13:56:10 -0400323 hdrs bazel.LabelListAttribute
324
Chris Parsons2c788392021-08-10 11:58:07 -0400325 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000326
327 // Not affected by arch variants
328 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500329 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000330 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400331
332 localIncludes bazel.StringListAttribute
333 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400334
Liz Kammer1263d9b2021-12-10 14:28:20 -0500335 includes BazelIncludes
336
Liz Kammer12615db2021-09-28 09:19:17 -0400337 protoSrcs bazel.LabelListAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400338 aidlSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000339
340 stubsSymbolFile *string
341 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700342
343 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500344
345 suffix bazel.StringAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000346}
347
Liz Kammercac7f692021-12-16 14:19:32 -0500348type filterOutFn func(string) bool
349
350func filterOutStdFlag(flag string) bool {
351 return strings.HasPrefix(flag, "-std=")
352}
353
Alix1be00d42022-05-16 22:56:04 +0000354func filterOutClangUnknownCflags(flag string) bool {
355 for _, f := range config.ClangUnknownCflags {
356 if f == flag {
357 return true
358 }
359 }
360 return false
361}
362
363func parseCommandLineFlags(soongFlags []string, noCoptsTokenization bool, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400364 var result []string
365 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000366 skipFlag := false
367 for _, filter := range filterOut {
368 if filter != nil && filter(flag) {
369 skipFlag = true
370 }
371 }
372 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500373 continue
374 }
Liz Kammere6583482021-10-19 13:56:10 -0400375 // Soong's cflags can contain spaces, like `-include header.h`. For
376 // Bazel's copts, split them up to be compatible with the
377 // no_copts_tokenization feature.
Alix1be00d42022-05-16 22:56:04 +0000378 if noCoptsTokenization {
379 result = append(result, strings.Split(flag, " ")...)
380 } else {
381 // Soong's Version Script and Dynamic List Properties are added as flags
382 // to Bazel's linkopts using "($location label)" syntax.
383 // Splitting on spaces would separate this into two different flags
384 // "($ location" and "label)"
385 result = append(result, flag)
386 }
Liz Kammere6583482021-10-19 13:56:10 -0400387 }
388 return result
389}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000390
Jingwen Chen55bc8202021-11-02 06:40:51 +0000391func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400392 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
393 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
394 if srcsList, ok := parseSrcs(ctx, props); ok {
395 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400396 }
397
Liz Kammere6583482021-10-19 13:56:10 -0400398 localIncludeDirs := props.Local_include_dirs
399 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500400 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400401 if includeBuildDirectory(props.Include_build_directory) {
402 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400403 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000404 }
405
Liz Kammere6583482021-10-19 13:56:10 -0400406 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
407 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
408
Cole Faust5fa4e962022-08-22 14:31:04 -0700409 instructionSet := proptools.StringDefault(props.Instruction_set, "")
410 if instructionSet == "arm" {
411 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm", "-arm_isa_thumb"})
412 } else if instructionSet != "" && instructionSet != "thumb" {
413 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
414 }
415
Liz Kammercac7f692021-12-16 14:19:32 -0500416 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
417 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
418 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
419 // cases.
Alix1be00d42022-05-16 22:56:04 +0000420 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, true, filterOutStdFlag, filterOutClangUnknownCflags))
421 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, true, nil))
422 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, true, filterOutClangUnknownCflags))
423 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, true, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400424 ca.rtti.SetSelectValue(axis, config, props.Rtti)
425}
426
Jingwen Chen55bc8202021-11-02 06:40:51 +0000427func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000428 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
429 if stlProps, ok := props.(*StlProperties); ok {
430 if stlProps.Stl == nil {
431 return
432 }
433 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400434 stl := deduplicateStlInput(*stlProps.Stl)
435 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000436 } else if ca.stl != stlProps.Stl {
437 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 -0400438 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000439 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000440 })
Liz Kammere6583482021-10-19 13:56:10 -0400441}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000442
Jingwen Chen55bc8202021-11-02 06:40:51 +0000443func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400444 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400445 "Cflags": &ca.copts,
446 "Asflags": &ca.asFlags,
447 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400448 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400449 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000450 if productConfigProps, exists := productVariableProps[propName]; exists {
451 for productConfigProp, prop := range productConfigProps {
452 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400453 if !ok {
454 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
455 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000456 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
457 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400458 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400459 }
460 }
Liz Kammere6583482021-10-19 13:56:10 -0400461}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400462
Jingwen Chen55bc8202021-11-02 06:40:51 +0000463func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400464 ca.srcs.ResolveExcludes()
465 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
466
Liz Kammer12615db2021-09-28 09:19:17 -0400467 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400468 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400469
Liz Kammere6583482021-10-19 13:56:10 -0400470 for p, lla := range partitionedSrcs {
471 // if there are no sources, there is no need for headers
472 if lla.IsEmpty() {
473 continue
474 }
475 lla.Append(implementationHdrs)
476 partitionedSrcs[p] = lla
477 }
478
479 ca.srcs = partitionedSrcs[cppSrcPartition]
480 ca.cSrcs = partitionedSrcs[cSrcPartition]
481 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700482 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000483 ca.lSrcs = partitionedSrcs[lSrcPartition]
484 ca.llSrcs = partitionedSrcs[llSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400485
486 ca.absoluteIncludes.DeduplicateAxesFromBase()
487 ca.localIncludes.DeduplicateAxesFromBase()
488}
489
490// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000491func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400492 anySrcs := false
493 // Add srcs-like dependencies such as generated files.
494 // First create a LabelList containing these dependencies, then merge the values with srcs.
495 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
496 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
497 anySrcs = true
498 }
499
500 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400501
Liz Kammere6583482021-10-19 13:56:10 -0400502 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
503 anySrcs = true
504 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400505
Liz Kammere6583482021-10-19 13:56:10 -0400506 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
507}
508
Liz Kammera5a29de2022-05-25 23:19:37 -0400509func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
510 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500511 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
512 // Defaults are handled by the toolchain definition.
513 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400514 stdVal := proptools.StringDefault(std, defaultVal)
515 if stdVal == "experimental" || stdVal == defaultVal {
516 if stdVal == "experimental" {
517 stdVal = prefix + "_std_experimental"
518 }
519 if !useGnu {
520 stdVal += "_no_gnu"
521 }
522 } else if !useGnu {
523 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500524 }
525
Liz Kammera5a29de2022-05-25 23:19:37 -0400526 if stdVal == defaultVal {
527 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500528 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400529 return &stdVal
530}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500531
Liz Kammera5a29de2022-05-25 23:19:37 -0400532func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
533 useGnu := useGnuExtensions(gnu_extensions)
534
535 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400536}
537
Liz Kammer1263d9b2021-12-10 14:28:20 -0500538// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
539// is fully-qualified.
540// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
541func packageFromLabel(label string) (string, bool) {
542 split := strings.Split(label, ":")
543 if len(split) != 2 {
544 return "", false
545 }
546 if split[0] == "" {
547 return ".", false
548 }
549 // remove leading "//"
550 return split[0][2:], true
551}
552
553// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
554func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
555 for _, hdr := range labelList.Includes {
556 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
557 absolute = append(absolute, pkg)
558 } else if pkg != "" {
559 relative = append(relative, pkg)
560 }
561 }
562 return relative, absolute
563}
564
Cole Faust7071a052022-07-29 15:58:33 -0700565type YasmAttributes struct {
566 Srcs bazel.LabelListAttribute
567 Flags bazel.StringListAttribute
568 Include_dirs bazel.StringListAttribute
569}
570
571func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
572 if ca.asmSrcs.IsEmpty() {
573 return nil
574 }
575
576 // Yasm needs the include directories from both local_includes and
577 // export_include_dirs. We don't care about actually exporting them from the
578 // yasm rule though, because they will also be present on the cc_ rule that
579 // wraps this yasm rule.
580 includes := ca.localIncludes.Clone()
581 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
582 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
583 if len(flagExporterProperties.Export_include_dirs) > 0 {
584 x := bazel.StringListAttribute{}
585 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
586 includes.Append(x)
587 }
588 }
589 })
590
591 ctx.CreateBazelTargetModule(
592 bazel.BazelTargetModuleProperties{
593 Rule_class: "yasm",
594 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
595 },
596 android.CommonAttributes{Name: m.Name() + "_yasm"},
597 &YasmAttributes{
598 Srcs: ca.asmSrcs,
599 Flags: ca.asFlags,
600 Include_dirs: *includes,
601 })
602
603 // We only want to add a dependency on the _yasm target if there are asm
604 // sources in the current configuration. If there are unconfigured asm
605 // sources, always add the dependency. Otherwise, add the dependency only
606 // on the configuration axes and values that had asm sources.
607 if len(ca.asmSrcs.Value.Includes) > 0 {
608 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
609 }
610
611 ret := &bazel.LabelAttribute{}
612 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
613 for config := range ca.asmSrcs.ConfigurableValues[axis] {
614 ret.SetSelectValue(axis, config, bazel.Label{Label: ":" + m.Name() + "_yasm"})
615 }
616 }
617 return ret
618}
619
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000620// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400621func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400622 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
623 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000624 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400625
626 var implementationHdrs bazel.LabelListAttribute
627
628 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
629 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
630 for axis, configMap := range cp {
631 if _, ok := axisToConfigs[axis]; !ok {
632 axisToConfigs[axis] = map[string]bool{}
633 }
634 for config, _ := range configMap {
635 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400636 }
637 }
638 }
Liz Kammere6583482021-10-19 13:56:10 -0400639 allAxesAndConfigs(archVariantCompilerProps)
640 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000641 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400642
Liz Kammere6583482021-10-19 13:56:10 -0400643 compilerAttrs := compilerAttributes{}
644 linkerAttrs := linkerAttributes{}
645
646 for axis, configs := range axisToConfigs {
647 for config, _ := range configs {
648 var allHdrs []string
649 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
650 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000651 if baseCompilerProps.Lex != nil {
652 compilerAttrs.lexopts.SetSelectValue(axis, config, baseCompilerProps.Lex.Flags)
653 }
Liz Kammere6583482021-10-19 13:56:10 -0400654 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
655 }
656
657 var exportHdrs []string
658
659 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
660 exportHdrs = baseLinkerProps.Export_generated_headers
661
662 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
663 }
664 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
665 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
666 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500667
668 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
669 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
670 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
671
672 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
673 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
674 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400675
Liz Kammer1263d9b2021-12-10 14:28:20 -0500676 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400677
Liz Kammer1263d9b2021-12-10 14:28:20 -0500678 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
679 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400680
Liz Kammer1263d9b2021-12-10 14:28:20 -0500681 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000682
683 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
684 if axis == bazel.NoConfigAxis {
685 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
686 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
687 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500688 if suffix := libraryProps.Suffix; suffix != nil {
689 compilerAttrs.suffix.SetSelectValue(axis, config, suffix)
690 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000691 }
Liz Kammere6583482021-10-19 13:56:10 -0400692 }
693 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400694
Liz Kammere6583482021-10-19 13:56:10 -0400695 compilerAttrs.convertStlProps(ctx, module)
696 (&linkerAttrs).convertStripProps(ctx, module)
697
Yu Liu8d82ac52022-05-17 15:13:28 -0700698 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
699 !Bool(module.coverage.Properties.Native_coverage) {
700 // Native_coverage is arch neutral
701 (&linkerAttrs).features.Append(bazel.MakeStringListAttribute([]string{"-coverage"}))
702 }
703
Liz Kammere6583482021-10-19 13:56:10 -0400704 productVariableProps := android.ProductVariableProperties(ctx)
705
706 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
707 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
708
709 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500710 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400711
Cole Faust7071a052022-07-29 15:58:33 -0700712 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
713
Liz Kammer12615db2021-09-28 09:19:17 -0400714 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
715
716 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
717 // which. This will add the newly generated proto library to the appropriate attribute and nothing
718 // to the other
719 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
720 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400721
722 aidlDep := bp2buildCcAidlLibrary(ctx, module, compilerAttrs.aidlSrcs)
723 if aidlDep != nil {
724 if lib, ok := module.linker.(*libraryDecorator); ok {
725 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
726 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
727 } else {
728 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
729 }
730 }
731 }
Liz Kammer12615db2021-09-28 09:19:17 -0400732
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000733 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
734 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
735 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
736
Cole Faust5fa4e962022-08-22 14:31:04 -0700737 features := compilerAttrs.features.Clone().Append(linkerAttrs.features)
738 features.DeduplicateAxesFromBase()
739
Liz Kammere6583482021-10-19 13:56:10 -0400740 return baseAttributes{
741 compilerAttrs,
742 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700743 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400744 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400745 aidlDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000746 }
747}
748
Vinh Tran9f6796a2022-08-16 13:10:31 -0400749func bp2buildCcAidlLibrary(
750 ctx android.Bp2buildMutatorContext,
751 m *Module,
Vinh Trana3b8b782022-09-14 11:40:24 -0400752 aidlLabelList bazel.LabelListAttribute,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400753) *bazel.LabelAttribute {
Vinh Trana3b8b782022-09-14 11:40:24 -0400754 if !aidlLabelList.IsEmpty() {
755 aidlLibs, aidlSrcs := aidlLabelList.Partition(func(src bazel.Label) bool {
756 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
757 fg.ShouldConvertToAidlLibrary(ctx) {
758 return true
759 }
760 return false
761 })
Vinh Tran9f6796a2022-08-16 13:10:31 -0400762
Vinh Trana3b8b782022-09-14 11:40:24 -0400763 if !aidlSrcs.IsEmpty() {
764 aidlLibName := m.Name() + "_aidl_library"
765 ctx.CreateBazelTargetModule(
766 bazel.BazelTargetModuleProperties{
767 Rule_class: "aidl_library",
768 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
769 },
770 android.CommonAttributes{Name: aidlLibName},
771 &aidlLibraryAttributes{
772 Srcs: aidlSrcs,
773 },
774 )
775 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
776 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400777
Vinh Trana3b8b782022-09-14 11:40:24 -0400778 if !aidlLibs.IsEmpty() {
779 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
780 ctx.CreateBazelTargetModule(
781 bazel.BazelTargetModuleProperties{
782 Rule_class: "cc_aidl_library",
783 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
784 },
785 android.CommonAttributes{Name: ccAidlLibrarylabel},
786 &ccAidlLibraryAttributes{
787 Deps: aidlLibs,
788 },
789 )
790 label := &bazel.LabelAttribute{
791 Value: &bazel.Label{
792 Label: ":" + ccAidlLibrarylabel,
793 },
794 }
795 return label
796 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400797 }
798
Vinh Trana3b8b782022-09-14 11:40:24 -0400799 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -0400800}
801
Yu Liufc603162022-03-01 15:44:08 -0800802func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000803 return sdkAttributes{
804 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800805 Min_sdk_version: module.Properties.Min_sdk_version,
806 }
807}
808
809type sdkAttributes struct {
810 Sdk_version *string
811 Min_sdk_version *string
812}
813
Jingwen Chen107c0de2021-04-09 10:43:12 +0000814// Convenience struct to hold all attributes parsed from linker properties.
815type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500816 deps bazel.LabelListAttribute
817 implementationDeps bazel.LabelListAttribute
818 dynamicDeps bazel.LabelListAttribute
819 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -0700820 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -0500821 wholeArchiveDeps bazel.LabelListAttribute
822 implementationWholeArchiveDeps bazel.LabelListAttribute
823 systemDynamicDeps bazel.LabelListAttribute
824 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400825
Jingwen Chen6ada5892021-09-17 11:38:09 +0000826 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000827 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500828 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000829 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400830 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000831 stripKeepSymbols bazel.BoolAttribute
832 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
833 stripKeepSymbolsList bazel.StringListAttribute
834 stripAll bazel.BoolAttribute
835 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400836 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400837}
838
Liz Kammer54309532021-12-14 12:21:22 -0500839var (
840 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
841)
842
Jingwen Chen55bc8202021-11-02 06:40:51 +0000843func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400844 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
845 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400846
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400847 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
848 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammere6583482021-10-19 13:56:10 -0400849 // Excludes to parallel Soong:
850 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400851 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
852
Liz Kammere6583482021-10-19 13:56:10 -0400853 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400854
Liz Kammere6583482021-10-19 13:56:10 -0400855 headerLibs := android.FirstUniqueStrings(props.Header_libs)
856 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400857
Liz Kammere6583482021-10-19 13:56:10 -0400858 (&hDeps.export).Append(staticDeps.export)
859 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000860
Liz Kammere6583482021-10-19 13:56:10 -0400861 (&hDeps.implementation).Append(staticDeps.implementation)
862 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400863
Liz Kammere6583482021-10-19 13:56:10 -0400864 systemSharedLibs := props.System_shared_libs
865 // systemSharedLibs distinguishes between nil/empty list behavior:
866 // nil -> use default values
867 // empty list -> no values specified
868 if len(systemSharedLibs) > 0 {
869 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
870 }
871 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
872
873 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500874 excludeSharedLibs := props.Exclude_shared_libs
875 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
876 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
877 })
878 for _, el := range usedSystem {
879 if la.usedSystemDynamicDepAsDynamicDep == nil {
880 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
881 }
882 la.usedSystemDynamicDepAsDynamicDep[el] = true
883 }
884
Liz Kammere6583482021-10-19 13:56:10 -0400885 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
886 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
887 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Wei Li81852ca2022-07-27 00:22:06 -0700888 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
889 // If a dependency in la.implementationDynamicDeps has stubs, its stub variant should be
890 // used when the dependency is linked in a APEX. The dependencies in NoConfigAxis and
891 // OsConfigurationAxis/OsAndroid are grouped by having stubs or not, so Bazel select()
892 // statement can be used to choose source/stub variants of them.
893 depsWithStubs := []bazel.Label{}
894 for _, l := range sharedDeps.implementation.Includes {
895 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
896 if m, ok := dep.(*Module); ok && m.HasStubsVariants() {
897 depsWithStubs = append(depsWithStubs, l)
898 }
899 }
900 if len(depsWithStubs) > 0 {
901 implDynamicDeps := bazel.SubtractBazelLabelList(sharedDeps.implementation, bazel.MakeLabelList(depsWithStubs))
902 la.implementationDynamicDeps.SetSelectValue(axis, config, implDynamicDeps)
903
904 stubLibLabels := []bazel.Label{}
905 for _, l := range depsWithStubs {
Liz Kammer91487d42022-09-13 11:27:11 -0400906 l.Label = l.Label + stubsSuffix
Wei Li81852ca2022-07-27 00:22:06 -0700907 stubLibLabels = append(stubLibLabels, l)
908 }
909 inApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex)
910 nonApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex)
911 defaultSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
912 if axis == bazel.NoConfigAxis {
913 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
914 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
915 (&defaultSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
916 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, inApexSelectValue)
917 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, nonApexSelectValue)
918 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, defaultSelectValue)
919 } else if config == bazel.OsAndroid {
920 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
921 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
922 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, inApexSelectValue)
923 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, nonApexSelectValue)
924 }
925 }
926 }
Liz Kammere6583482021-10-19 13:56:10 -0400927
928 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
929 axisFeatures = append(axisFeatures, "disable_pack_relocations")
930 }
931
932 if Bool(props.Allow_undefined_symbols) {
933 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
934 }
935
936 var linkerFlags []string
937 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -0500938 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -0400939 // binaries remove static flag if -shared is in the linker flags
940 if isBinary && android.InList("-shared", linkerFlags) {
941 axisFeatures = append(axisFeatures, "-static_flag")
942 }
943 }
944 if props.Version_script != nil {
945 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
946 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
947 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
948 }
Alix773adaa2022-04-27 17:49:34 +0000949
950 if props.Dynamic_list != nil {
951 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
952 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
953 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
954 }
955
Alix1be00d42022-05-16 22:56:04 +0000956 la.linkopts.SetSelectValue(axis, config, parseCommandLineFlags(linkerFlags, false, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400957 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
958
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500959 if axis == bazel.NoConfigAxis {
960 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
961 }
962
Liz Kammere6583482021-10-19 13:56:10 -0400963 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
964 if props.crt() != nil {
965 if axis == bazel.NoConfigAxis {
966 la.linkCrt.SetSelectValue(axis, config, props.crt())
967 } else if axis == bazel.ArchConfigurationAxis {
968 ctx.ModuleErrorf("nocrt is not supported for arch variants")
969 }
970 }
971
972 if axisFeatures != nil {
973 la.features.SetSelectValue(axis, config, axisFeatures)
974 }
Cole Faust6b29f592022-08-09 09:50:56 -0700975
976 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
977 if !runtimeDeps.IsEmpty() {
978 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
979 }
Liz Kammere6583482021-10-19 13:56:10 -0400980}
981
Jingwen Chen55bc8202021-11-02 06:40:51 +0000982func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000983 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
984 if stripProperties, ok := props.(*StripProperties); ok {
985 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
986 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
987 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
988 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
989 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000990 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000991 })
Liz Kammere6583482021-10-19 13:56:10 -0400992}
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000993
Jingwen Chen55bc8202021-11-02 06:40:51 +0000994func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +0000995
Liz Kammer47535c52021-06-02 16:02:22 -0400996 type productVarDep struct {
997 // the name of the corresponding excludes field, if one exists
998 excludesField string
999 // reference to the bazel attribute that should be set for the given product variable config
1000 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001001
Jingwen Chen55bc8202021-11-02 06:40:51 +00001002 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001003 }
1004
Zi Wang0a8a1292022-08-30 06:27:01 +00001005 // an intermediate attribute that holds Header_libs info, and will be appended to
1006 // implementationDeps at the end, to solve the confliction that both header_libs
1007 // and static_libs use implementationDeps.
1008 var headerDeps bazel.LabelListAttribute
1009
Liz Kammer47535c52021-06-02 16:02:22 -04001010 productVarToDepFields := map[string]productVarDep{
1011 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001012 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1013 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1014 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001015 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001016 }
1017
Liz Kammer47535c52021-06-02 16:02:22 -04001018 for name, dep := range productVarToDepFields {
1019 props, exists := productVariableProps[name]
1020 excludeProps, excludesExists := productVariableProps[dep.excludesField]
1021 // if neither an include or excludes property exists, then skip it
1022 if !exists && !excludesExists {
1023 continue
1024 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001025 // Collect all the configurations that an include or exclude property exists for.
1026 // We want to iterate all configurations rather than either the include or exclude because, for a
1027 // particular configuration, we may have either only an include or an exclude to handle.
1028 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
1029 for p := range props {
1030 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001031 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001032 for p := range excludeProps {
1033 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001034 }
1035
Jingwen Chen25825ca2021-11-15 12:28:43 +00001036 for productConfigProp := range productConfigProps {
1037 prop, includesExists := props[productConfigProp]
1038 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001039 var includes, excludes []string
1040 var ok bool
1041 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001042 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001043 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1044 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001045 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001046 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1047 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001048
Jingwen Chen58ff6802021-11-17 12:14:41 +00001049 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001050 dep.attribute.SetSelectValue(
1051 productConfigProp.ConfigurationAxis(),
1052 productConfigProp.SelectKey(),
1053 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1054 )
Liz Kammer47535c52021-06-02 16:02:22 -04001055 }
1056 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001057 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001058}
Liz Kammer47535c52021-06-02 16:02:22 -04001059
Liz Kammer54309532021-12-14 12:21:22 -05001060func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1061 // if system dynamic deps have the default value, any use of a system dynamic library used will
1062 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001063 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001064 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
1065 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001066 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001067 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1068 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001069 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001070 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1071 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001072
1073 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
1074 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, toRemove)
1075 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1076 for _, lib := range toRemove.Includes {
1077 lib.Label += stubsSuffix
1078 stubsToRemove = append(stubsToRemove, lib)
1079 }
1080 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001081 }
1082
Liz Kammere6583482021-10-19 13:56:10 -04001083 la.deps.ResolveExcludes()
1084 la.implementationDeps.ResolveExcludes()
1085 la.dynamicDeps.ResolveExcludes()
1086 la.implementationDynamicDeps.ResolveExcludes()
1087 la.wholeArchiveDeps.ResolveExcludes()
1088 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001089
Jingwen Chen91220d72021-03-24 02:18:33 -04001090}
1091
Jingwen Chened9c17d2021-04-13 07:14:55 +00001092// Relativize a list of root-relative paths with respect to the module's
1093// directory.
1094//
1095// include_dirs Soong prop are root-relative (b/183742505), but
1096// local_include_dirs, export_include_dirs and export_system_include_dirs are
1097// module dir relative. This function makes a list of paths entirely module dir
1098// relative.
1099//
1100// For the `include` attribute, Bazel wants the paths to be relative to the
1101// module.
1102func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001103 var relativePaths []string
1104 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001105 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1106 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1107 if err != nil {
1108 panic(err)
1109 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001110 relativePaths = append(relativePaths, relativePath)
1111 }
1112 return relativePaths
1113}
1114
Liz Kammer5fad5012021-09-09 14:08:21 -04001115// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1116// attributes.
1117type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001118 AbsoluteIncludes bazel.StringListAttribute
1119 Includes bazel.StringListAttribute
1120 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001121}
1122
Liz Kammer54549442022-05-11 13:55:06 -04001123func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001124 var exported BazelIncludes
1125 if includes != nil {
1126 exported = *includes
1127 } else {
1128 exported = BazelIncludes{}
1129 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001130 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1131 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1132 if len(flagExporterProperties.Export_include_dirs) > 0 {
1133 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1134 }
1135 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1136 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 -04001137 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001138 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001139 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001140 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001141 exported.Includes.DeduplicateAxesFromBase()
1142 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001143
Liz Kammer5fad5012021-09-09 14:08:21 -04001144 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001145}
Chris Parsons953b3562021-09-20 15:14:39 -04001146
Jingwen Chen55bc8202021-11-02 06:40:51 +00001147func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001148 label := android.BazelModuleLabel(ctx, m)
Chris Parsonsad876012022-08-20 14:48:32 -04001149 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GetBp2BuildAllowList().GenerateCcLibraryStaticOnly(m.Name()) {
Liz Kammer35ca77e2021-12-22 15:31:40 -05001150 label += "_bp2build_cc_library_static"
Chris Parsons953b3562021-09-20 15:14:39 -04001151 }
1152 return label
1153}
1154
Jingwen Chen55bc8202021-11-02 06:40:51 +00001155func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001156 // cc_library, at it's root name, propagates the shared library, which depends on the static
1157 // library.
1158 return android.BazelModuleLabel(ctx, m)
1159}
1160
Jingwen Chen55bc8202021-11-02 06:40:51 +00001161func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001162 label := bazelLabelForStaticModule(ctx, m)
1163 if aModule, ok := m.(android.Module); ok {
1164 if android.IsModulePrebuilt(aModule) {
1165 label += "_alwayslink"
1166 }
1167 }
1168 return label
1169}
1170
Jingwen Chen55bc8202021-11-02 06:40:51 +00001171func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001172 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1173}
1174
Jingwen Chen55bc8202021-11-02 06:40:51 +00001175func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001176 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1177}
1178
Jingwen Chen55bc8202021-11-02 06:40:51 +00001179func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001180 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1181}
1182
Jingwen Chen55bc8202021-11-02 06:40:51 +00001183func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001184 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1185}
1186
Jingwen Chen55bc8202021-11-02 06:40:51 +00001187func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001188 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1189}
1190
Jingwen Chen55bc8202021-11-02 06:40:51 +00001191func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001192 // This is not elegant, but bp2build's shared library targets only propagate
1193 // their header information as part of the normal C++ provider.
1194 return bazelLabelForSharedDeps(ctx, modules)
1195}
1196
Zi Wang0a8a1292022-08-30 06:27:01 +00001197func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1198 // This is only used when product_variable header_libs is processed, to follow
1199 // the pattern of depResolutionFunc
1200 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1201}
1202
Jingwen Chen55bc8202021-11-02 06:40:51 +00001203func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001204 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1205}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001206
1207type binaryLinkerAttrs struct {
1208 Linkshared *bool
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001209 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001210}
1211
Jingwen Chen55bc8202021-11-02 06:40:51 +00001212func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001213 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001214 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1215 linkerProps := props.(*BinaryLinkerProperties)
1216 staticExecutable := linkerProps.Static_executable
1217 if axis == bazel.NoConfigAxis {
1218 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1219 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001220 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001221 } else if staticExecutable != nil {
1222 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1223 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1224 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001225 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001226 if suffix := linkerProps.Suffix; suffix != nil {
1227 attrs.Suffix.SetSelectValue(axis, config, suffix)
1228 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001229 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001230
1231 return attrs
1232}