blob: e001d248999ccf3cf5ab61866da04f9db475680e [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 }
82 // If the filegroup is already converted to aidl_library, skip creating
83 // _c_srcs, _as_srcs, _cpp_srcs filegroups
84 fg, _ := m.(android.Bp2buildAidlLibrary)
85 if fg.ShouldConvertToAidlLibrary(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
Vinh Tran9f6796a2022-08-16 13:10:31 -0400509// Given a name in srcs prop, check to see if the name references a filegroup
510// and the filegroup is converted to aidl_library
511func isConvertedToAidlLibrary(ctx android.BazelConversionPathContext, name string) bool {
512 if module, ok := ctx.ModuleFromName(name); ok {
513 if android.IsFilegroup(ctx, module) {
514 if fg, ok := module.(android.Bp2buildAidlLibrary); ok {
515 return fg.ShouldConvertToAidlLibrary(ctx)
516 }
517 }
518 }
519 return false
520}
521
Liz Kammera5a29de2022-05-25 23:19:37 -0400522func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
523 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500524 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
525 // Defaults are handled by the toolchain definition.
526 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400527 stdVal := proptools.StringDefault(std, defaultVal)
528 if stdVal == "experimental" || stdVal == defaultVal {
529 if stdVal == "experimental" {
530 stdVal = prefix + "_std_experimental"
531 }
532 if !useGnu {
533 stdVal += "_no_gnu"
534 }
535 } else if !useGnu {
536 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500537 }
538
Liz Kammera5a29de2022-05-25 23:19:37 -0400539 if stdVal == defaultVal {
540 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500541 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400542 return &stdVal
543}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500544
Liz Kammera5a29de2022-05-25 23:19:37 -0400545func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
546 useGnu := useGnuExtensions(gnu_extensions)
547
548 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400549}
550
Liz Kammer1263d9b2021-12-10 14:28:20 -0500551// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
552// is fully-qualified.
553// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
554func packageFromLabel(label string) (string, bool) {
555 split := strings.Split(label, ":")
556 if len(split) != 2 {
557 return "", false
558 }
559 if split[0] == "" {
560 return ".", false
561 }
562 // remove leading "//"
563 return split[0][2:], true
564}
565
566// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
567func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
568 for _, hdr := range labelList.Includes {
569 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
570 absolute = append(absolute, pkg)
571 } else if pkg != "" {
572 relative = append(relative, pkg)
573 }
574 }
575 return relative, absolute
576}
577
Cole Faust7071a052022-07-29 15:58:33 -0700578type YasmAttributes struct {
579 Srcs bazel.LabelListAttribute
580 Flags bazel.StringListAttribute
581 Include_dirs bazel.StringListAttribute
582}
583
584func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
585 if ca.asmSrcs.IsEmpty() {
586 return nil
587 }
588
589 // Yasm needs the include directories from both local_includes and
590 // export_include_dirs. We don't care about actually exporting them from the
591 // yasm rule though, because they will also be present on the cc_ rule that
592 // wraps this yasm rule.
593 includes := ca.localIncludes.Clone()
594 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
595 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
596 if len(flagExporterProperties.Export_include_dirs) > 0 {
597 x := bazel.StringListAttribute{}
598 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
599 includes.Append(x)
600 }
601 }
602 })
603
604 ctx.CreateBazelTargetModule(
605 bazel.BazelTargetModuleProperties{
606 Rule_class: "yasm",
607 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
608 },
609 android.CommonAttributes{Name: m.Name() + "_yasm"},
610 &YasmAttributes{
611 Srcs: ca.asmSrcs,
612 Flags: ca.asFlags,
613 Include_dirs: *includes,
614 })
615
616 // We only want to add a dependency on the _yasm target if there are asm
617 // sources in the current configuration. If there are unconfigured asm
618 // sources, always add the dependency. Otherwise, add the dependency only
619 // on the configuration axes and values that had asm sources.
620 if len(ca.asmSrcs.Value.Includes) > 0 {
621 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
622 }
623
624 ret := &bazel.LabelAttribute{}
625 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
626 for config := range ca.asmSrcs.ConfigurableValues[axis] {
627 ret.SetSelectValue(axis, config, bazel.Label{Label: ":" + m.Name() + "_yasm"})
628 }
629 }
630 return ret
631}
632
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000633// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400634func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400635 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
636 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000637 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400638
639 var implementationHdrs bazel.LabelListAttribute
640
641 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
642 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
643 for axis, configMap := range cp {
644 if _, ok := axisToConfigs[axis]; !ok {
645 axisToConfigs[axis] = map[string]bool{}
646 }
647 for config, _ := range configMap {
648 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400649 }
650 }
651 }
Liz Kammere6583482021-10-19 13:56:10 -0400652 allAxesAndConfigs(archVariantCompilerProps)
653 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000654 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400655
Liz Kammere6583482021-10-19 13:56:10 -0400656 compilerAttrs := compilerAttributes{}
657 linkerAttrs := linkerAttributes{}
658
659 for axis, configs := range axisToConfigs {
660 for config, _ := range configs {
661 var allHdrs []string
662 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
663 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000664 if baseCompilerProps.Lex != nil {
665 compilerAttrs.lexopts.SetSelectValue(axis, config, baseCompilerProps.Lex.Flags)
666 }
Liz Kammere6583482021-10-19 13:56:10 -0400667 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
668 }
669
670 var exportHdrs []string
671
672 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
673 exportHdrs = baseLinkerProps.Export_generated_headers
674
675 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
676 }
677 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
678 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
679 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500680
681 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
682 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
683 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
684
685 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
686 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
687 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400688
Liz Kammer1263d9b2021-12-10 14:28:20 -0500689 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400690
Liz Kammer1263d9b2021-12-10 14:28:20 -0500691 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
692 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400693
Liz Kammer1263d9b2021-12-10 14:28:20 -0500694 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000695
696 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
697 if axis == bazel.NoConfigAxis {
698 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
699 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
700 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500701 if suffix := libraryProps.Suffix; suffix != nil {
702 compilerAttrs.suffix.SetSelectValue(axis, config, suffix)
703 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000704 }
Liz Kammere6583482021-10-19 13:56:10 -0400705 }
706 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400707
Liz Kammere6583482021-10-19 13:56:10 -0400708 compilerAttrs.convertStlProps(ctx, module)
709 (&linkerAttrs).convertStripProps(ctx, module)
710
Yu Liu8d82ac52022-05-17 15:13:28 -0700711 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
712 !Bool(module.coverage.Properties.Native_coverage) {
713 // Native_coverage is arch neutral
714 (&linkerAttrs).features.Append(bazel.MakeStringListAttribute([]string{"-coverage"}))
715 }
716
Liz Kammere6583482021-10-19 13:56:10 -0400717 productVariableProps := android.ProductVariableProperties(ctx)
718
719 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
720 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
721
722 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500723 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400724
Cole Faust7071a052022-07-29 15:58:33 -0700725 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
726
Liz Kammer12615db2021-09-28 09:19:17 -0400727 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
728
729 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
730 // which. This will add the newly generated proto library to the appropriate attribute and nothing
731 // to the other
732 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
733 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400734
735 aidlDep := bp2buildCcAidlLibrary(ctx, module, compilerAttrs.aidlSrcs)
736 if aidlDep != nil {
737 if lib, ok := module.linker.(*libraryDecorator); ok {
738 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
739 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
740 } else {
741 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
742 }
743 }
744 }
Liz Kammer12615db2021-09-28 09:19:17 -0400745
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000746 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
747 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
748 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
749
Cole Faust5fa4e962022-08-22 14:31:04 -0700750 features := compilerAttrs.features.Clone().Append(linkerAttrs.features)
751 features.DeduplicateAxesFromBase()
752
Liz Kammere6583482021-10-19 13:56:10 -0400753 return baseAttributes{
754 compilerAttrs,
755 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700756 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400757 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400758 aidlDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000759 }
760}
761
Vinh Tran9f6796a2022-08-16 13:10:31 -0400762func bp2buildAidlLibraries(
763 ctx android.Bp2buildMutatorContext,
764 m *Module,
765 aidlSrcs bazel.LabelListAttribute,
766) bazel.LabelList {
767 var aidlLibraries bazel.LabelList
768 var directAidlSrcs bazel.LabelList
769
770 // Make a list of labels that correspond to filegroups that are already converted to aidl_library
771 for _, aidlSrc := range aidlSrcs.Value.Includes {
772 src := aidlSrc.OriginalModuleName
773 if isConvertedToAidlLibrary(ctx, src) {
774 module, _ := ctx.ModuleFromName(src)
775 fg, _ := module.(android.Bp2buildAidlLibrary)
776 aidlLibraries.Add(&bazel.Label{
777 Label: fg.GetAidlLibraryLabel(ctx),
778 })
779 } else {
780 directAidlSrcs.Add(&aidlSrc)
781 }
782 }
783
784 if len(directAidlSrcs.Includes) > 0 {
785 aidlLibraryLabel := m.Name() + "_aidl_library"
786 ctx.CreateBazelTargetModule(
787 bazel.BazelTargetModuleProperties{
788 Rule_class: "aidl_library",
789 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
790 },
791 android.CommonAttributes{Name: aidlLibraryLabel},
792 &aidlLibraryAttributes{
793 Srcs: bazel.MakeLabelListAttribute(directAidlSrcs),
794 },
795 )
796 aidlLibraries.Add(&bazel.Label{
797 Label: ":" + aidlLibraryLabel,
798 })
799 }
800 return aidlLibraries
801}
802
803func bp2buildCcAidlLibrary(
804 ctx android.Bp2buildMutatorContext,
805 m *Module,
806 aidlSrcs bazel.LabelListAttribute,
807) *bazel.LabelAttribute {
808 suffix := "_cc_aidl_library"
809 ccAidlLibrarylabel := m.Name() + suffix
810
811 aidlLibraries := bp2buildAidlLibraries(ctx, m, aidlSrcs)
812
813 if aidlLibraries.IsEmpty() {
814 return nil
815 }
816
817 ctx.CreateBazelTargetModule(
818 bazel.BazelTargetModuleProperties{
819 Rule_class: "cc_aidl_library",
820 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
821 },
822 android.CommonAttributes{Name: ccAidlLibrarylabel},
823 &ccAidlLibraryAttributes{
824 Deps: bazel.MakeLabelListAttribute(aidlLibraries),
825 },
826 )
827
828 label := &bazel.LabelAttribute{
829 Value: &bazel.Label{
830 Label: ":" + ccAidlLibrarylabel,
831 },
832 }
833 return label
834}
835
Yu Liufc603162022-03-01 15:44:08 -0800836func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000837 return sdkAttributes{
838 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800839 Min_sdk_version: module.Properties.Min_sdk_version,
840 }
841}
842
843type sdkAttributes struct {
844 Sdk_version *string
845 Min_sdk_version *string
846}
847
Jingwen Chen107c0de2021-04-09 10:43:12 +0000848// Convenience struct to hold all attributes parsed from linker properties.
849type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500850 deps bazel.LabelListAttribute
851 implementationDeps bazel.LabelListAttribute
852 dynamicDeps bazel.LabelListAttribute
853 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -0700854 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -0500855 wholeArchiveDeps bazel.LabelListAttribute
856 implementationWholeArchiveDeps bazel.LabelListAttribute
857 systemDynamicDeps bazel.LabelListAttribute
858 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400859
Jingwen Chen6ada5892021-09-17 11:38:09 +0000860 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000861 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500862 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000863 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400864 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000865 stripKeepSymbols bazel.BoolAttribute
866 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
867 stripKeepSymbolsList bazel.StringListAttribute
868 stripAll bazel.BoolAttribute
869 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400870 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400871}
872
Liz Kammer54309532021-12-14 12:21:22 -0500873var (
874 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
875)
876
Jingwen Chen55bc8202021-11-02 06:40:51 +0000877func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400878 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
879 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400880
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400881 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
882 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammere6583482021-10-19 13:56:10 -0400883 // Excludes to parallel Soong:
884 // 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 -0400885 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
886
Liz Kammere6583482021-10-19 13:56:10 -0400887 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, staticLibs, props.Exclude_static_libs, props.Export_static_lib_headers, bazelLabelForStaticDepsExcludes)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400888
Liz Kammere6583482021-10-19 13:56:10 -0400889 headerLibs := android.FirstUniqueStrings(props.Header_libs)
890 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400891
Liz Kammere6583482021-10-19 13:56:10 -0400892 (&hDeps.export).Append(staticDeps.export)
893 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000894
Liz Kammere6583482021-10-19 13:56:10 -0400895 (&hDeps.implementation).Append(staticDeps.implementation)
896 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400897
Liz Kammere6583482021-10-19 13:56:10 -0400898 systemSharedLibs := props.System_shared_libs
899 // systemSharedLibs distinguishes between nil/empty list behavior:
900 // nil -> use default values
901 // empty list -> no values specified
902 if len(systemSharedLibs) > 0 {
903 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
904 }
905 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
906
907 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500908 excludeSharedLibs := props.Exclude_shared_libs
909 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
910 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
911 })
912 for _, el := range usedSystem {
913 if la.usedSystemDynamicDepAsDynamicDep == nil {
914 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
915 }
916 la.usedSystemDynamicDepAsDynamicDep[el] = true
917 }
918
Liz Kammere6583482021-10-19 13:56:10 -0400919 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(ctx, !isBinary, sharedLibs, props.Exclude_shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDepsExcludes)
920 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
921 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Wei Li81852ca2022-07-27 00:22:06 -0700922 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
923 // If a dependency in la.implementationDynamicDeps has stubs, its stub variant should be
924 // used when the dependency is linked in a APEX. The dependencies in NoConfigAxis and
925 // OsConfigurationAxis/OsAndroid are grouped by having stubs or not, so Bazel select()
926 // statement can be used to choose source/stub variants of them.
927 depsWithStubs := []bazel.Label{}
928 for _, l := range sharedDeps.implementation.Includes {
929 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
930 if m, ok := dep.(*Module); ok && m.HasStubsVariants() {
931 depsWithStubs = append(depsWithStubs, l)
932 }
933 }
934 if len(depsWithStubs) > 0 {
935 implDynamicDeps := bazel.SubtractBazelLabelList(sharedDeps.implementation, bazel.MakeLabelList(depsWithStubs))
936 la.implementationDynamicDeps.SetSelectValue(axis, config, implDynamicDeps)
937
938 stubLibLabels := []bazel.Label{}
939 for _, l := range depsWithStubs {
Liz Kammer91487d42022-09-13 11:27:11 -0400940 l.Label = l.Label + stubsSuffix
Wei Li81852ca2022-07-27 00:22:06 -0700941 stubLibLabels = append(stubLibLabels, l)
942 }
943 inApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex)
944 nonApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex)
945 defaultSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
946 if axis == bazel.NoConfigAxis {
947 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
948 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
949 (&defaultSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
950 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, inApexSelectValue)
951 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, nonApexSelectValue)
952 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, defaultSelectValue)
953 } else if config == bazel.OsAndroid {
954 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
955 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
956 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, inApexSelectValue)
957 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, nonApexSelectValue)
958 }
959 }
960 }
Liz Kammere6583482021-10-19 13:56:10 -0400961
962 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
963 axisFeatures = append(axisFeatures, "disable_pack_relocations")
964 }
965
966 if Bool(props.Allow_undefined_symbols) {
967 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
968 }
969
970 var linkerFlags []string
971 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -0500972 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -0400973 // binaries remove static flag if -shared is in the linker flags
974 if isBinary && android.InList("-shared", linkerFlags) {
975 axisFeatures = append(axisFeatures, "-static_flag")
976 }
977 }
978 if props.Version_script != nil {
979 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
980 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
981 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
982 }
Alix773adaa2022-04-27 17:49:34 +0000983
984 if props.Dynamic_list != nil {
985 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
986 la.additionalLinkerInputs.SetSelectValue(axis, config, bazel.LabelList{Includes: []bazel.Label{label}})
987 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
988 }
989
Alix1be00d42022-05-16 22:56:04 +0000990 la.linkopts.SetSelectValue(axis, config, parseCommandLineFlags(linkerFlags, false, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400991 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
992
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500993 if axis == bazel.NoConfigAxis {
994 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
995 }
996
Liz Kammere6583482021-10-19 13:56:10 -0400997 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
998 if props.crt() != nil {
999 if axis == bazel.NoConfigAxis {
1000 la.linkCrt.SetSelectValue(axis, config, props.crt())
1001 } else if axis == bazel.ArchConfigurationAxis {
1002 ctx.ModuleErrorf("nocrt is not supported for arch variants")
1003 }
1004 }
1005
1006 if axisFeatures != nil {
1007 la.features.SetSelectValue(axis, config, axisFeatures)
1008 }
Cole Faust6b29f592022-08-09 09:50:56 -07001009
1010 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1011 if !runtimeDeps.IsEmpty() {
1012 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1013 }
Liz Kammere6583482021-10-19 13:56:10 -04001014}
1015
Jingwen Chen55bc8202021-11-02 06:40:51 +00001016func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001017 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1018 if stripProperties, ok := props.(*StripProperties); ok {
1019 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1020 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1021 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1022 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1023 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001024 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001025 })
Liz Kammere6583482021-10-19 13:56:10 -04001026}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001027
Jingwen Chen55bc8202021-11-02 06:40:51 +00001028func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001029
Liz Kammer47535c52021-06-02 16:02:22 -04001030 type productVarDep struct {
1031 // the name of the corresponding excludes field, if one exists
1032 excludesField string
1033 // reference to the bazel attribute that should be set for the given product variable config
1034 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001035
Jingwen Chen55bc8202021-11-02 06:40:51 +00001036 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001037 }
1038
Zi Wang0a8a1292022-08-30 06:27:01 +00001039 // an intermediate attribute that holds Header_libs info, and will be appended to
1040 // implementationDeps at the end, to solve the confliction that both header_libs
1041 // and static_libs use implementationDeps.
1042 var headerDeps bazel.LabelListAttribute
1043
Liz Kammer47535c52021-06-02 16:02:22 -04001044 productVarToDepFields := map[string]productVarDep{
1045 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001046 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1047 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1048 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001049 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001050 }
1051
Liz Kammer47535c52021-06-02 16:02:22 -04001052 for name, dep := range productVarToDepFields {
1053 props, exists := productVariableProps[name]
1054 excludeProps, excludesExists := productVariableProps[dep.excludesField]
1055 // if neither an include or excludes property exists, then skip it
1056 if !exists && !excludesExists {
1057 continue
1058 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001059 // Collect all the configurations that an include or exclude property exists for.
1060 // We want to iterate all configurations rather than either the include or exclude because, for a
1061 // particular configuration, we may have either only an include or an exclude to handle.
1062 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
1063 for p := range props {
1064 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001065 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001066 for p := range excludeProps {
1067 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001068 }
1069
Jingwen Chen25825ca2021-11-15 12:28:43 +00001070 for productConfigProp := range productConfigProps {
1071 prop, includesExists := props[productConfigProp]
1072 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001073 var includes, excludes []string
1074 var ok bool
1075 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001076 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001077 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1078 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001079 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001080 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1081 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001082
Jingwen Chen58ff6802021-11-17 12:14:41 +00001083 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001084 dep.attribute.SetSelectValue(
1085 productConfigProp.ConfigurationAxis(),
1086 productConfigProp.SelectKey(),
1087 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1088 )
Liz Kammer47535c52021-06-02 16:02:22 -04001089 }
1090 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001091 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001092}
Liz Kammer47535c52021-06-02 16:02:22 -04001093
Liz Kammer54309532021-12-14 12:21:22 -05001094func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1095 // if system dynamic deps have the default value, any use of a system dynamic library used will
1096 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001097 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001098 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
1099 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001100 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001101 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1102 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001103 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001104 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1105 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001106
1107 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
1108 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, toRemove)
1109 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1110 for _, lib := range toRemove.Includes {
1111 lib.Label += stubsSuffix
1112 stubsToRemove = append(stubsToRemove, lib)
1113 }
1114 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001115 }
1116
Liz Kammere6583482021-10-19 13:56:10 -04001117 la.deps.ResolveExcludes()
1118 la.implementationDeps.ResolveExcludes()
1119 la.dynamicDeps.ResolveExcludes()
1120 la.implementationDynamicDeps.ResolveExcludes()
1121 la.wholeArchiveDeps.ResolveExcludes()
1122 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001123
Jingwen Chen91220d72021-03-24 02:18:33 -04001124}
1125
Jingwen Chened9c17d2021-04-13 07:14:55 +00001126// Relativize a list of root-relative paths with respect to the module's
1127// directory.
1128//
1129// include_dirs Soong prop are root-relative (b/183742505), but
1130// local_include_dirs, export_include_dirs and export_system_include_dirs are
1131// module dir relative. This function makes a list of paths entirely module dir
1132// relative.
1133//
1134// For the `include` attribute, Bazel wants the paths to be relative to the
1135// module.
1136func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001137 var relativePaths []string
1138 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001139 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1140 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1141 if err != nil {
1142 panic(err)
1143 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001144 relativePaths = append(relativePaths, relativePath)
1145 }
1146 return relativePaths
1147}
1148
Liz Kammer5fad5012021-09-09 14:08:21 -04001149// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1150// attributes.
1151type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001152 AbsoluteIncludes bazel.StringListAttribute
1153 Includes bazel.StringListAttribute
1154 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001155}
1156
Liz Kammer54549442022-05-11 13:55:06 -04001157func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001158 var exported BazelIncludes
1159 if includes != nil {
1160 exported = *includes
1161 } else {
1162 exported = BazelIncludes{}
1163 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001164 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1165 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1166 if len(flagExporterProperties.Export_include_dirs) > 0 {
1167 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1168 }
1169 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1170 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 -04001171 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001172 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001173 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001174 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001175 exported.Includes.DeduplicateAxesFromBase()
1176 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001177
Liz Kammer5fad5012021-09-09 14:08:21 -04001178 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001179}
Chris Parsons953b3562021-09-20 15:14:39 -04001180
Jingwen Chen55bc8202021-11-02 06:40:51 +00001181func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001182 label := android.BazelModuleLabel(ctx, m)
Chris Parsonsad876012022-08-20 14:48:32 -04001183 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GetBp2BuildAllowList().GenerateCcLibraryStaticOnly(m.Name()) {
Liz Kammer35ca77e2021-12-22 15:31:40 -05001184 label += "_bp2build_cc_library_static"
Chris Parsons953b3562021-09-20 15:14:39 -04001185 }
1186 return label
1187}
1188
Jingwen Chen55bc8202021-11-02 06:40:51 +00001189func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001190 // cc_library, at it's root name, propagates the shared library, which depends on the static
1191 // library.
1192 return android.BazelModuleLabel(ctx, m)
1193}
1194
Jingwen Chen55bc8202021-11-02 06:40:51 +00001195func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001196 label := bazelLabelForStaticModule(ctx, m)
1197 if aModule, ok := m.(android.Module); ok {
1198 if android.IsModulePrebuilt(aModule) {
1199 label += "_alwayslink"
1200 }
1201 }
1202 return label
1203}
1204
Jingwen Chen55bc8202021-11-02 06:40:51 +00001205func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001206 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1207}
1208
Jingwen Chen55bc8202021-11-02 06:40:51 +00001209func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001210 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1211}
1212
Jingwen Chen55bc8202021-11-02 06:40:51 +00001213func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001214 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1215}
1216
Jingwen Chen55bc8202021-11-02 06:40:51 +00001217func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001218 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1219}
1220
Jingwen Chen55bc8202021-11-02 06:40:51 +00001221func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001222 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1223}
1224
Jingwen Chen55bc8202021-11-02 06:40:51 +00001225func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001226 // This is not elegant, but bp2build's shared library targets only propagate
1227 // their header information as part of the normal C++ provider.
1228 return bazelLabelForSharedDeps(ctx, modules)
1229}
1230
Zi Wang0a8a1292022-08-30 06:27:01 +00001231func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1232 // This is only used when product_variable header_libs is processed, to follow
1233 // the pattern of depResolutionFunc
1234 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1235}
1236
Jingwen Chen55bc8202021-11-02 06:40:51 +00001237func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001238 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1239}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001240
1241type binaryLinkerAttrs struct {
1242 Linkshared *bool
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001243 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001244}
1245
Jingwen Chen55bc8202021-11-02 06:40:51 +00001246func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001247 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001248 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1249 linkerProps := props.(*BinaryLinkerProperties)
1250 staticExecutable := linkerProps.Static_executable
1251 if axis == bazel.NoConfigAxis {
1252 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1253 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001254 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001255 } else if staticExecutable != nil {
1256 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1257 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1258 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001259 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001260 if suffix := linkerProps.Suffix; suffix != nil {
1261 attrs.Suffix.SetSelectValue(axis, config, suffix)
1262 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001263 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001264
1265 return attrs
1266}