blob: 83368a392039547c5d2ec8e683b1b60917989100 [file] [log] [blame]
Jingwen Chen91220d72021-03-24 02:18:33 -04001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
Cole Faust7071a052022-07-29 15:58:33 -07007// http://www.apache.org/licenses/LICENSE-2.0
Jingwen Chen91220d72021-03-24 02:18:33 -04008//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14package cc
15
16import (
Liz Kammerd2871182021-10-04 13:54:37 -040017 "fmt"
Jingwen Chened9c17d2021-04-13 07:14:55 +000018 "path/filepath"
Jingwen Chen3950cd62021-05-12 04:33:00 +000019 "strings"
Chris Parsons484e50a2021-05-13 15:13:04 -040020
21 "android/soong/android"
22 "android/soong/bazel"
Alix1be00d42022-05-16 22:56:04 +000023 "android/soong/cc/config"
Liz Kammer7a210ac2021-09-22 15:52:58 -040024
Chris Parsons953b3562021-09-20 15:14:39 -040025 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040026
27 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040028)
29
Liz Kammerae3994e2021-10-19 09:45:48 -040030const (
Trevor Radcliffecee4e052022-09-06 19:31:25 +000031 cSrcPartition = "c"
32 asSrcPartition = "as"
33 asmSrcPartition = "asm"
34 lSrcPartition = "l"
35 llSrcPartition = "ll"
36 cppSrcPartition = "cpp"
37 protoSrcPartition = "proto"
38 aidlSrcPartition = "aidl"
39 syspropSrcPartition = "sysprop"
Liz Kammer91487d42022-09-13 11:27:11 -040040
41 stubsSuffix = "_stub_libs_current"
Liz Kammerae3994e2021-10-19 09:45:48 -040042)
43
Liz Kammer2222c6b2021-05-24 15:41:47 -040044// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000045// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040046type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040047 Srcs bazel.LabelListAttribute
48 Srcs_c bazel.LabelListAttribute
49 Srcs_as bazel.LabelListAttribute
50 Srcs_aidl bazel.LabelListAttribute
51 Hdrs bazel.LabelListAttribute
52 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000053
Liz Kammer12615db2021-09-28 09:19:17 -040054 Deps bazel.LabelListAttribute
55 Implementation_deps bazel.LabelListAttribute
56 Dynamic_deps bazel.LabelListAttribute
57 Implementation_dynamic_deps bazel.LabelListAttribute
58 Whole_archive_deps bazel.LabelListAttribute
59 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070060 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040061
62 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050063
64 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080065
Yu Liu8d82ac52022-05-17 15:13:28 -070066 Native_coverage bazel.BoolAttribute
67
Yu Liufc603162022-03-01 15:44:08 -080068 sdkAttributes
Jingwen Chen53681ef2021-04-29 08:15:13 +000069}
70
Sam Delmericoc7681022022-02-04 21:01:20 +000071// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +000072func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -040073 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
74 // macro.
75 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -040076 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
77
78 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -040079 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -040080 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
81 return labelStr, false
82 }
Yu Liu2aa806b2022-09-01 11:54:47 -070083 // If the filegroup is already converted to aidl_library or proto_library,
84 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
85 fg, _ := m.(android.FileGroupAsLibrary)
86 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -040087 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +000088 }
Liz Kammer12615db2021-09-28 09:19:17 -040089 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -040090 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +000091 }
92
Liz Kammer57e2e7a2021-09-20 12:55:02 -040093 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +000094 labels := bazel.LabelPartitions{
95 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -050096 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
97 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -070098 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -040099 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000100 // TODO(http://b/231968910): If there is ever a filegroup target that
101 // contains .l or .ll files we will need to find a way to add a
102 // LabelMapper for these that identifies these filegroups and
103 // converts them appropriately
104 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
105 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400106 // C++ is the "catch-all" group, and comprises generated sources because we don't
107 // know the language of these sources until the genrule is executed.
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000108 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
109 syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
Sam Delmericoc7681022022-02-04 21:01:20 +0000110 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000111
Sam Delmericoc7681022022-02-04 21:01:20 +0000112 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000113}
114
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000115// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000116func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000117 lib, ok := module.compiler.(*libraryDecorator)
118 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400119 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000120 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000121 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
122}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000123
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000124// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000125func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000126 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000127}
128
129// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000130func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000131 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400132}
133
Liz Kammer7a210ac2021-09-22 15:52:58 -0400134type depsPartition struct {
135 export bazel.LabelList
136 implementation bazel.LabelList
137}
138
Jingwen Chen55bc8202021-11-02 06:40:51 +0000139type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400140
Jingwen Chen55bc8202021-11-02 06:40:51 +0000141func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400142 if !exportsDeps {
143 return depsPartition{
144 implementation: fn(ctx, allDeps),
145 }
146 }
147
Liz Kammer7a210ac2021-09-22 15:52:58 -0400148 implementation, export := android.FilterList(allDeps, exportedDeps)
149
150 return depsPartition{
151 export: fn(ctx, export),
152 implementation: fn(ctx, implementation),
153 }
154}
155
Jingwen Chen55bc8202021-11-02 06:40:51 +0000156type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400157
Jingwen Chen55bc8202021-11-02 06:40:51 +0000158func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400159 if !exportsDeps {
160 return depsPartition{
161 implementation: fn(ctx, allDeps, excludes),
162 }
163 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400164 implementation, export := android.FilterList(allDeps, exportedDeps)
165
166 return depsPartition{
167 export: fn(ctx, export, excludes),
168 implementation: fn(ctx, implementation, excludes),
169 }
170}
171
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000172// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000173func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400174 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000175
Liz Kammer9abd62d2021-05-21 08:37:59 -0400176 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Alix1be00d42022-05-16 22:56:04 +0000177 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, true, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000178 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400179 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400180
Liz Kammer2b8004b2021-10-04 13:55:44 -0400181 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400182 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
183 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
184
Liz Kammer2b8004b2021-10-04 13:55:44 -0400185 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400186 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
187 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
188
189 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500190 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000191 }
Liz Kammer135bf552021-08-11 10:46:06 -0400192 // system_dynamic_deps distinguishes between nil/empty list behavior:
193 // nil -> use default values
194 // empty list -> no values specified
195 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000196
197 if isStatic {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000198 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
199 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
200 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000201 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000202 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000203 } else {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000204 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
205 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
206 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000207 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000208 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000209 }
210
Liz Kammerae3994e2021-10-19 09:45:48 -0400211 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
212 attrs.Srcs = partitionedSrcs[cppSrcPartition]
213 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
214 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000215
Liz Kammer12615db2021-09-28 09:19:17 -0400216 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
217 // TODO(b/208815215): determine whether this is used and add support if necessary
218 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
219 }
220
Jingwen Chenbcf53042021-05-26 04:42:42 +0000221 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000222}
223
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400224// Convenience struct to hold all attributes parsed from prebuilt properties.
225type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000226 Src bazel.LabelAttribute
227 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400228}
229
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000230// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000231func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) prebuiltAttributes {
232 manySourceFileError := func(axis bazel.ConfigurationAxis, config string) {
233 ctx.ModuleErrorf("Bp2BuildParsePrebuiltLibraryProps: Expected at most one source file for %s %s\n", axis, config)
234 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400235 var srcLabelAttribute bazel.LabelAttribute
236
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000237 parseSrcs := func(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, srcs []string) {
238 if len(srcs) > 1 {
239 manySourceFileError(axis, config)
240 return
241 } else if len(srcs) == 0 {
242 return
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400243 }
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000244 if srcLabelAttribute.SelectValue(axis, config) != nil {
245 manySourceFileError(axis, config)
246 return
247 }
248
249 src := android.BazelLabelForModuleSrcSingle(ctx, srcs[0])
250 srcLabelAttribute.SetSelectValue(axis, config, src)
251 }
252
253 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
254 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
255 parseSrcs(ctx, axis, config, prebuiltLinkerProperties.Srcs)
256 }
257 })
258
259 var enabledLabelAttribute bazel.BoolAttribute
260 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
261 if props.Enabled != nil {
262 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
263 }
264 parseSrcs(ctx, axis, config, props.Srcs)
265 }
266
267 if isStatic {
268 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
269 if staticProperties, ok := props.(*StaticProperties); ok {
270 parseAttrs(axis, config, staticProperties.Static)
271 }
272 })
273 } else {
274 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
275 if sharedProperties, ok := props.(*SharedProperties); ok {
276 parseAttrs(axis, config, sharedProperties.Shared)
277 }
278 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400279 }
280
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400281 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000282 Src: srcLabelAttribute,
283 Enabled: enabledLabelAttribute,
284 }
285}
286
287func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
288 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
289 for config, props := range configToProps {
290 parseFunc(axis, config, props)
291 }
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400292 }
293}
294
Liz Kammere6583482021-10-19 13:56:10 -0400295type baseAttributes struct {
296 compilerAttributes
297 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400298
Cole Faust5fa4e962022-08-22 14:31:04 -0700299 // A combination of compilerAttributes.features and linkerAttributes.features
300 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400301 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400302 aidlDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400303}
304
Jingwen Chen107c0de2021-04-09 10:43:12 +0000305// Convenience struct to hold all attributes parsed from compiler properties.
306type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400307 // Options for all languages
308 copts bazel.StringListAttribute
309 // Assembly options and sources
310 asFlags bazel.StringListAttribute
311 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700312 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400313 // C options and sources
314 conlyFlags bazel.StringListAttribute
315 cSrcs bazel.LabelListAttribute
316 // C++ options and sources
317 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000318 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400319
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000320 // Lex sources and options
321 lSrcs bazel.LabelListAttribute
322 llSrcs bazel.LabelListAttribute
323 lexopts bazel.StringListAttribute
324
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000325 // Sysprop sources
326 syspropSrcs bazel.LabelListAttribute
327
Liz Kammere6583482021-10-19 13:56:10 -0400328 hdrs bazel.LabelListAttribute
329
Chris Parsons2c788392021-08-10 11:58:07 -0400330 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000331
332 // Not affected by arch variants
333 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500334 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000335 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400336
337 localIncludes bazel.StringListAttribute
338 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400339
Liz Kammer1263d9b2021-12-10 14:28:20 -0500340 includes BazelIncludes
341
Liz Kammer12615db2021-09-28 09:19:17 -0400342 protoSrcs bazel.LabelListAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400343 aidlSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000344
345 stubsSymbolFile *string
346 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700347
348 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500349
350 suffix bazel.StringAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000351}
352
Liz Kammercac7f692021-12-16 14:19:32 -0500353type filterOutFn func(string) bool
354
355func filterOutStdFlag(flag string) bool {
356 return strings.HasPrefix(flag, "-std=")
357}
358
Alix1be00d42022-05-16 22:56:04 +0000359func filterOutClangUnknownCflags(flag string) bool {
360 for _, f := range config.ClangUnknownCflags {
361 if f == flag {
362 return true
363 }
364 }
365 return false
366}
367
368func parseCommandLineFlags(soongFlags []string, noCoptsTokenization bool, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400369 var result []string
370 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000371 skipFlag := false
372 for _, filter := range filterOut {
373 if filter != nil && filter(flag) {
374 skipFlag = true
375 }
376 }
377 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500378 continue
379 }
Liz Kammere6583482021-10-19 13:56:10 -0400380 // Soong's cflags can contain spaces, like `-include header.h`. For
381 // Bazel's copts, split them up to be compatible with the
382 // no_copts_tokenization feature.
Alix1be00d42022-05-16 22:56:04 +0000383 if noCoptsTokenization {
384 result = append(result, strings.Split(flag, " ")...)
385 } else {
386 // Soong's Version Script and Dynamic List Properties are added as flags
387 // to Bazel's linkopts using "($location label)" syntax.
388 // Splitting on spaces would separate this into two different flags
389 // "($ location" and "label)"
390 result = append(result, flag)
391 }
Liz Kammere6583482021-10-19 13:56:10 -0400392 }
393 return result
394}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000395
Jingwen Chen55bc8202021-11-02 06:40:51 +0000396func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400397 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
398 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
399 if srcsList, ok := parseSrcs(ctx, props); ok {
400 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400401 }
402
Liz Kammere6583482021-10-19 13:56:10 -0400403 localIncludeDirs := props.Local_include_dirs
404 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500405 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400406 if includeBuildDirectory(props.Include_build_directory) {
407 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400408 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000409 }
410
Liz Kammere6583482021-10-19 13:56:10 -0400411 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
412 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
413
Cole Faust5fa4e962022-08-22 14:31:04 -0700414 instructionSet := proptools.StringDefault(props.Instruction_set, "")
415 if instructionSet == "arm" {
416 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm", "-arm_isa_thumb"})
417 } else if instructionSet != "" && instructionSet != "thumb" {
418 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
419 }
420
Liz Kammercac7f692021-12-16 14:19:32 -0500421 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
422 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
423 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
424 // cases.
Alix1be00d42022-05-16 22:56:04 +0000425 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, true, filterOutStdFlag, filterOutClangUnknownCflags))
426 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, true, nil))
427 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, true, filterOutClangUnknownCflags))
428 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, true, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400429 ca.rtti.SetSelectValue(axis, config, props.Rtti)
430}
431
Jingwen Chen55bc8202021-11-02 06:40:51 +0000432func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000433 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
434 if stlProps, ok := props.(*StlProperties); ok {
435 if stlProps.Stl == nil {
436 return
437 }
438 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400439 stl := deduplicateStlInput(*stlProps.Stl)
440 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000441 } else if ca.stl != stlProps.Stl {
442 ctx.ModuleErrorf("Unsupported conversion: module with different stl for different variants: %s and %s", *ca.stl, stlProps.Stl)
Liz Kammer9abd62d2021-05-21 08:37:59 -0400443 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000444 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000445 })
Liz Kammere6583482021-10-19 13:56:10 -0400446}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000447
Jingwen Chen55bc8202021-11-02 06:40:51 +0000448func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400449 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400450 "Cflags": &ca.copts,
451 "Asflags": &ca.asFlags,
452 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400453 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400454 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000455 if productConfigProps, exists := productVariableProps[propName]; exists {
456 for productConfigProp, prop := range productConfigProps {
457 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400458 if !ok {
459 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
460 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000461 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
462 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400463 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400464 }
465 }
Liz Kammere6583482021-10-19 13:56:10 -0400466}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400467
Jingwen Chen55bc8202021-11-02 06:40:51 +0000468func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400469 ca.srcs.ResolveExcludes()
470 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
471
Liz Kammer12615db2021-09-28 09:19:17 -0400472 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400473 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400474
Liz Kammere6583482021-10-19 13:56:10 -0400475 for p, lla := range partitionedSrcs {
476 // if there are no sources, there is no need for headers
477 if lla.IsEmpty() {
478 continue
479 }
480 lla.Append(implementationHdrs)
481 partitionedSrcs[p] = lla
482 }
483
484 ca.srcs = partitionedSrcs[cppSrcPartition]
485 ca.cSrcs = partitionedSrcs[cSrcPartition]
486 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700487 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000488 ca.lSrcs = partitionedSrcs[lSrcPartition]
489 ca.llSrcs = partitionedSrcs[llSrcPartition]
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000490 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400491
492 ca.absoluteIncludes.DeduplicateAxesFromBase()
493 ca.localIncludes.DeduplicateAxesFromBase()
494}
495
496// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000497func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400498 anySrcs := false
499 // Add srcs-like dependencies such as generated files.
500 // First create a LabelList containing these dependencies, then merge the values with srcs.
501 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
502 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
503 anySrcs = true
504 }
505
506 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400507
Liz Kammere6583482021-10-19 13:56:10 -0400508 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
509 anySrcs = true
510 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400511
Liz Kammere6583482021-10-19 13:56:10 -0400512 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
513}
514
Liz Kammera5a29de2022-05-25 23:19:37 -0400515func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
516 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500517 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
518 // Defaults are handled by the toolchain definition.
519 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400520 stdVal := proptools.StringDefault(std, defaultVal)
521 if stdVal == "experimental" || stdVal == defaultVal {
522 if stdVal == "experimental" {
523 stdVal = prefix + "_std_experimental"
524 }
525 if !useGnu {
526 stdVal += "_no_gnu"
527 }
528 } else if !useGnu {
529 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500530 }
531
Liz Kammera5a29de2022-05-25 23:19:37 -0400532 if stdVal == defaultVal {
533 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500534 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400535 return &stdVal
536}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500537
Liz Kammera5a29de2022-05-25 23:19:37 -0400538func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
539 useGnu := useGnuExtensions(gnu_extensions)
540
541 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400542}
543
Liz Kammer1263d9b2021-12-10 14:28:20 -0500544// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
545// is fully-qualified.
546// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
547func packageFromLabel(label string) (string, bool) {
548 split := strings.Split(label, ":")
549 if len(split) != 2 {
550 return "", false
551 }
552 if split[0] == "" {
553 return ".", false
554 }
555 // remove leading "//"
556 return split[0][2:], true
557}
558
559// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
560func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
561 for _, hdr := range labelList.Includes {
562 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
563 absolute = append(absolute, pkg)
564 } else if pkg != "" {
565 relative = append(relative, pkg)
566 }
567 }
568 return relative, absolute
569}
570
Cole Faust7071a052022-07-29 15:58:33 -0700571type YasmAttributes struct {
572 Srcs bazel.LabelListAttribute
573 Flags bazel.StringListAttribute
574 Include_dirs bazel.StringListAttribute
575}
576
577func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
578 if ca.asmSrcs.IsEmpty() {
579 return nil
580 }
581
582 // Yasm needs the include directories from both local_includes and
583 // export_include_dirs. We don't care about actually exporting them from the
584 // yasm rule though, because they will also be present on the cc_ rule that
585 // wraps this yasm rule.
586 includes := ca.localIncludes.Clone()
587 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
588 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
589 if len(flagExporterProperties.Export_include_dirs) > 0 {
590 x := bazel.StringListAttribute{}
591 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
592 includes.Append(x)
593 }
594 }
595 })
596
597 ctx.CreateBazelTargetModule(
598 bazel.BazelTargetModuleProperties{
599 Rule_class: "yasm",
600 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
601 },
602 android.CommonAttributes{Name: m.Name() + "_yasm"},
603 &YasmAttributes{
604 Srcs: ca.asmSrcs,
605 Flags: ca.asFlags,
606 Include_dirs: *includes,
607 })
608
609 // We only want to add a dependency on the _yasm target if there are asm
610 // sources in the current configuration. If there are unconfigured asm
611 // sources, always add the dependency. Otherwise, add the dependency only
612 // on the configuration axes and values that had asm sources.
613 if len(ca.asmSrcs.Value.Includes) > 0 {
614 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
615 }
616
617 ret := &bazel.LabelAttribute{}
618 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
619 for config := range ca.asmSrcs.ConfigurableValues[axis] {
620 ret.SetSelectValue(axis, config, bazel.Label{Label: ":" + m.Name() + "_yasm"})
621 }
622 }
623 return ret
624}
625
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000626// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400627func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400628 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
629 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000630 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400631
632 var implementationHdrs bazel.LabelListAttribute
633
634 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
635 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
636 for axis, configMap := range cp {
637 if _, ok := axisToConfigs[axis]; !ok {
638 axisToConfigs[axis] = map[string]bool{}
639 }
640 for config, _ := range configMap {
641 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400642 }
643 }
644 }
Liz Kammere6583482021-10-19 13:56:10 -0400645 allAxesAndConfigs(archVariantCompilerProps)
646 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000647 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400648
Liz Kammere6583482021-10-19 13:56:10 -0400649 compilerAttrs := compilerAttributes{}
650 linkerAttrs := linkerAttributes{}
651
652 for axis, configs := range axisToConfigs {
653 for config, _ := range configs {
654 var allHdrs []string
655 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
656 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000657 if baseCompilerProps.Lex != nil {
658 compilerAttrs.lexopts.SetSelectValue(axis, config, baseCompilerProps.Lex.Flags)
659 }
Liz Kammere6583482021-10-19 13:56:10 -0400660 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
661 }
662
663 var exportHdrs []string
664
665 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
666 exportHdrs = baseLinkerProps.Export_generated_headers
667
668 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
669 }
670 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
671 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
672 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500673
674 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
675 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
676 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
677
678 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
679 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
680 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400681
Liz Kammer1263d9b2021-12-10 14:28:20 -0500682 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400683
Liz Kammer1263d9b2021-12-10 14:28:20 -0500684 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
685 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400686
Liz Kammer1263d9b2021-12-10 14:28:20 -0500687 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000688
689 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
690 if axis == bazel.NoConfigAxis {
691 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
692 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
693 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500694 if suffix := libraryProps.Suffix; suffix != nil {
695 compilerAttrs.suffix.SetSelectValue(axis, config, suffix)
696 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000697 }
Liz Kammere6583482021-10-19 13:56:10 -0400698 }
699 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400700
Liz Kammere6583482021-10-19 13:56:10 -0400701 compilerAttrs.convertStlProps(ctx, module)
702 (&linkerAttrs).convertStripProps(ctx, module)
703
Yu Liu8d82ac52022-05-17 15:13:28 -0700704 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
705 !Bool(module.coverage.Properties.Native_coverage) {
706 // Native_coverage is arch neutral
707 (&linkerAttrs).features.Append(bazel.MakeStringListAttribute([]string{"-coverage"}))
708 }
709
Liz Kammere6583482021-10-19 13:56:10 -0400710 productVariableProps := android.ProductVariableProperties(ctx)
711
712 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
713 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
714
715 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500716 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400717
Cole Faust7071a052022-07-29 15:58:33 -0700718 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
719
Liz Kammer12615db2021-09-28 09:19:17 -0400720 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
721
722 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
723 // which. This will add the newly generated proto library to the appropriate attribute and nothing
724 // to the other
725 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
726 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400727
Vinh Tran395a1e92022-09-16 18:27:29 -0400728 aidlDep := bp2buildCcAidlLibrary(ctx, module, compilerAttrs.aidlSrcs, linkerAttrs)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400729 if aidlDep != nil {
730 if lib, ok := module.linker.(*libraryDecorator); ok {
731 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
732 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
733 } else {
734 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
735 }
736 }
737 }
Liz Kammer12615db2021-09-28 09:19:17 -0400738
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000739 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
740 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
741 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
742
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000743 if !compilerAttrs.syspropSrcs.IsEmpty() {
744 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
745 }
746
Cole Faust5fa4e962022-08-22 14:31:04 -0700747 features := compilerAttrs.features.Clone().Append(linkerAttrs.features)
748 features.DeduplicateAxesFromBase()
749
Liz Kammere6583482021-10-19 13:56:10 -0400750 return baseAttributes{
751 compilerAttrs,
752 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700753 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400754 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400755 aidlDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000756 }
757}
758
Vinh Tran9f6796a2022-08-16 13:10:31 -0400759func bp2buildCcAidlLibrary(
760 ctx android.Bp2buildMutatorContext,
761 m *Module,
Vinh Trana3b8b782022-09-14 11:40:24 -0400762 aidlLabelList bazel.LabelListAttribute,
Vinh Tran395a1e92022-09-16 18:27:29 -0400763 linkerAttrs linkerAttributes,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400764) *bazel.LabelAttribute {
Vinh Trana3b8b782022-09-14 11:40:24 -0400765 if !aidlLabelList.IsEmpty() {
766 aidlLibs, aidlSrcs := aidlLabelList.Partition(func(src bazel.Label) bool {
767 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
768 fg.ShouldConvertToAidlLibrary(ctx) {
769 return true
770 }
771 return false
772 })
Vinh Tran9f6796a2022-08-16 13:10:31 -0400773
Vinh Trana3b8b782022-09-14 11:40:24 -0400774 if !aidlSrcs.IsEmpty() {
775 aidlLibName := m.Name() + "_aidl_library"
776 ctx.CreateBazelTargetModule(
777 bazel.BazelTargetModuleProperties{
778 Rule_class: "aidl_library",
779 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
780 },
781 android.CommonAttributes{Name: aidlLibName},
782 &aidlLibraryAttributes{
783 Srcs: aidlSrcs,
784 },
785 )
786 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
787 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400788
Vinh Trana3b8b782022-09-14 11:40:24 -0400789 if !aidlLibs.IsEmpty() {
790 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
Vinh Tran395a1e92022-09-16 18:27:29 -0400791 // Since cc_aidl_library only needs the dynamic deps (aka shared libs) from the parent cc library for compiling,
792 // we err on the side of not re-exporting the headers of the dynamic deps from cc_aidl_lirary
793 // because the parent cc library already has all the dynamic deps
794 implementationDynamicDeps := bazel.MakeLabelListAttribute(
795 bazel.AppendBazelLabelLists(
796 linkerAttrs.dynamicDeps.Value,
797 linkerAttrs.implementationDynamicDeps.Value,
798 ),
799 )
800
Vinh Trana3b8b782022-09-14 11:40:24 -0400801 ctx.CreateBazelTargetModule(
802 bazel.BazelTargetModuleProperties{
803 Rule_class: "cc_aidl_library",
804 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
805 },
806 android.CommonAttributes{Name: ccAidlLibrarylabel},
807 &ccAidlLibraryAttributes{
Vinh Tran395a1e92022-09-16 18:27:29 -0400808 Deps: aidlLibs,
809 Implementation_dynamic_deps: implementationDynamicDeps,
Vinh Trana3b8b782022-09-14 11:40:24 -0400810 },
811 )
812 label := &bazel.LabelAttribute{
813 Value: &bazel.Label{
814 Label: ":" + ccAidlLibrarylabel,
815 },
816 }
817 return label
818 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400819 }
820
Vinh Trana3b8b782022-09-14 11:40:24 -0400821 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -0400822}
823
Yu Liufc603162022-03-01 15:44:08 -0800824func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000825 return sdkAttributes{
826 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800827 Min_sdk_version: module.Properties.Min_sdk_version,
828 }
829}
830
831type sdkAttributes struct {
832 Sdk_version *string
833 Min_sdk_version *string
834}
835
Jingwen Chen107c0de2021-04-09 10:43:12 +0000836// Convenience struct to hold all attributes parsed from linker properties.
837type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500838 deps bazel.LabelListAttribute
839 implementationDeps bazel.LabelListAttribute
840 dynamicDeps bazel.LabelListAttribute
841 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -0700842 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -0500843 wholeArchiveDeps bazel.LabelListAttribute
844 implementationWholeArchiveDeps bazel.LabelListAttribute
845 systemDynamicDeps bazel.LabelListAttribute
846 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400847
Jingwen Chen6ada5892021-09-17 11:38:09 +0000848 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000849 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500850 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000851 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400852 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000853 stripKeepSymbols bazel.BoolAttribute
854 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
855 stripKeepSymbolsList bazel.StringListAttribute
856 stripAll bazel.BoolAttribute
857 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400858 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400859}
860
Liz Kammer54309532021-12-14 12:21:22 -0500861var (
862 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -0400863 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -0500864)
865
Vinh Tran85fb07c2022-09-16 16:17:48 -0400866// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
867// since all libs are already excluded by default
868func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, isBinary bool, props *BaseLinkerProperties) {
869 sharedLibsForNonApex := maybePartitionExportedAndImplementationsDeps(
870 ctx,
871 true,
872 props.Target.Apex.Exclude_shared_libs,
873 props.Export_shared_lib_headers,
874 bazelLabelForSharedDeps,
875 )
876 dynamicDeps := la.dynamicDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
877 implDynamicDeps := la.implementationDynamicDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
878 (&dynamicDeps).Append(sharedLibsForNonApex.export)
879 (&implDynamicDeps).Append(sharedLibsForNonApex.implementation)
880 la.dynamicDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, dynamicDeps)
881 la.implementationDynamicDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, implDynamicDeps)
882
883 staticLibsForNonApex := maybePartitionExportedAndImplementationsDeps(
884 ctx,
885 !isBinary,
886 props.Target.Apex.Exclude_static_libs,
887 props.Export_static_lib_headers,
888 bazelLabelForSharedDeps,
889 )
890 deps := la.deps.SelectValue(bazel.InApexAxis, bazel.NonApex)
891 implDeps := la.implementationDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
892 (&deps).Append(staticLibsForNonApex.export)
893 (&implDeps).Append(staticLibsForNonApex.implementation)
894 la.deps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, deps)
895 la.implementationDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, implDeps)
896}
897
Jingwen Chen55bc8202021-11-02 06:40:51 +0000898func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400899 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
900 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400901
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400902 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -0400903 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
904 if axis == bazel.NoConfigAxis {
905 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
906 if proptools.Bool(props.Use_version_lib) {
907 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
908 // remove from static libs so there is no duplicate dependency
909 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
910 // only add the dep if it is not in progress
911 if !versionLibAlreadyInDeps {
912 if isBinary {
913 wholeStaticLibs = append(wholeStaticLibs, versionLib)
914 } else {
915 la.implementationWholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, []string{versionLib}, props.Exclude_static_libs))
916 }
917 }
918 }
919 }
920
Liz Kammere6583482021-10-19 13:56:10 -0400921 // Excludes to parallel Soong:
922 // https://cs.android.com/android/platform/superproject/+/master:build/soong/cc/linker.go;l=247-249;drc=088b53577dde6e40085ffd737a1ae96ad82fc4b0
Liz Kammerbaced712022-09-16 09:01:29 -0400923 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400924
Vinh Tran85fb07c2022-09-16 16:17:48 -0400925 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
926 ctx,
927 !isBinary,
928 staticLibs,
929 // Exclude static libs in Exclude_static_libs and Target.Apex.Exclude_static_libs props
930 append(props.Exclude_static_libs, props.Target.Apex.Exclude_static_libs...),
931 props.Export_static_lib_headers,
932 bazelLabelForStaticDepsExcludes,
933 )
Liz Kammer7a210ac2021-09-22 15:52:58 -0400934
Liz Kammere6583482021-10-19 13:56:10 -0400935 headerLibs := android.FirstUniqueStrings(props.Header_libs)
936 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400937
Liz Kammere6583482021-10-19 13:56:10 -0400938 (&hDeps.export).Append(staticDeps.export)
939 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000940
Liz Kammere6583482021-10-19 13:56:10 -0400941 (&hDeps.implementation).Append(staticDeps.implementation)
942 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400943
Liz Kammere6583482021-10-19 13:56:10 -0400944 systemSharedLibs := props.System_shared_libs
945 // systemSharedLibs distinguishes between nil/empty list behavior:
946 // nil -> use default values
947 // empty list -> no values specified
948 if len(systemSharedLibs) > 0 {
949 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
950 }
951 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
952
953 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500954 excludeSharedLibs := props.Exclude_shared_libs
955 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
956 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
957 })
958 for _, el := range usedSystem {
959 if la.usedSystemDynamicDepAsDynamicDep == nil {
960 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
961 }
962 la.usedSystemDynamicDepAsDynamicDep[el] = true
963 }
964
Vinh Tran85fb07c2022-09-16 16:17:48 -0400965 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
966 ctx,
967 !isBinary,
968 sharedLibs,
969 // Exclude shared libs in Exclude_shared_libs and Target.Apex.Exclude_shared_libs props
970 append(props.Exclude_shared_libs, props.Target.Apex.Exclude_shared_libs...),
971 props.Export_shared_lib_headers,
972 bazelLabelForSharedDepsExcludes,
973 )
Liz Kammere6583482021-10-19 13:56:10 -0400974 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
975 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Vinh Tran85fb07c2022-09-16 16:17:48 -0400976 la.resolveTargetApexProp(ctx, isBinary, props)
977
Wei Li81852ca2022-07-27 00:22:06 -0700978 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
979 // If a dependency in la.implementationDynamicDeps has stubs, its stub variant should be
980 // used when the dependency is linked in a APEX. The dependencies in NoConfigAxis and
981 // OsConfigurationAxis/OsAndroid are grouped by having stubs or not, so Bazel select()
982 // statement can be used to choose source/stub variants of them.
983 depsWithStubs := []bazel.Label{}
984 for _, l := range sharedDeps.implementation.Includes {
985 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
986 if m, ok := dep.(*Module); ok && m.HasStubsVariants() {
987 depsWithStubs = append(depsWithStubs, l)
988 }
989 }
990 if len(depsWithStubs) > 0 {
991 implDynamicDeps := bazel.SubtractBazelLabelList(sharedDeps.implementation, bazel.MakeLabelList(depsWithStubs))
992 la.implementationDynamicDeps.SetSelectValue(axis, config, implDynamicDeps)
993
994 stubLibLabels := []bazel.Label{}
995 for _, l := range depsWithStubs {
Liz Kammer91487d42022-09-13 11:27:11 -0400996 l.Label = l.Label + stubsSuffix
Wei Li81852ca2022-07-27 00:22:06 -0700997 stubLibLabels = append(stubLibLabels, l)
998 }
999 inApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex)
1000 nonApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex)
1001 defaultSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
1002 if axis == bazel.NoConfigAxis {
1003 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
1004 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
1005 (&defaultSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
Trevor Radcliffe0ed6b7d2022-09-12 20:19:26 +00001006 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1007 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
1008 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
Wei Li81852ca2022-07-27 00:22:06 -07001009 } else if config == bazel.OsAndroid {
1010 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
1011 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
Trevor Radcliffe0ed6b7d2022-09-12 20:19:26 +00001012 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1013 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
Wei Li81852ca2022-07-27 00:22:06 -07001014 }
1015 }
1016 }
Liz Kammere6583482021-10-19 13:56:10 -04001017
1018 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1019 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1020 }
1021
1022 if Bool(props.Allow_undefined_symbols) {
1023 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1024 }
1025
1026 var linkerFlags []string
1027 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001028 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001029 // binaries remove static flag if -shared is in the linker flags
1030 if isBinary && android.InList("-shared", linkerFlags) {
1031 axisFeatures = append(axisFeatures, "-static_flag")
1032 }
1033 }
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001034 additionalLinkerInputs := bazel.LabelList{}
Liz Kammere6583482021-10-19 13:56:10 -04001035 if props.Version_script != nil {
1036 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001037 additionalLinkerInputs.Add(&label)
Liz Kammere6583482021-10-19 13:56:10 -04001038 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
1039 }
Alix773adaa2022-04-27 17:49:34 +00001040
1041 if props.Dynamic_list != nil {
1042 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001043 additionalLinkerInputs.Add(&label)
Alix773adaa2022-04-27 17:49:34 +00001044 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1045 }
1046
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001047 la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
Alix1be00d42022-05-16 22:56:04 +00001048 la.linkopts.SetSelectValue(axis, config, parseCommandLineFlags(linkerFlags, false, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -04001049 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
1050
1051 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
1052 if props.crt() != nil {
1053 if axis == bazel.NoConfigAxis {
1054 la.linkCrt.SetSelectValue(axis, config, props.crt())
1055 } else if axis == bazel.ArchConfigurationAxis {
1056 ctx.ModuleErrorf("nocrt is not supported for arch variants")
1057 }
1058 }
1059
1060 if axisFeatures != nil {
1061 la.features.SetSelectValue(axis, config, axisFeatures)
1062 }
Cole Faust6b29f592022-08-09 09:50:56 -07001063
1064 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1065 if !runtimeDeps.IsEmpty() {
1066 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1067 }
Liz Kammere6583482021-10-19 13:56:10 -04001068}
1069
Jingwen Chen55bc8202021-11-02 06:40:51 +00001070func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001071 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1072 if stripProperties, ok := props.(*StripProperties); ok {
1073 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1074 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1075 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1076 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1077 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001078 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001079 })
Liz Kammere6583482021-10-19 13:56:10 -04001080}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001081
Jingwen Chen55bc8202021-11-02 06:40:51 +00001082func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001083
Liz Kammer47535c52021-06-02 16:02:22 -04001084 type productVarDep struct {
1085 // the name of the corresponding excludes field, if one exists
1086 excludesField string
1087 // reference to the bazel attribute that should be set for the given product variable config
1088 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001089
Jingwen Chen55bc8202021-11-02 06:40:51 +00001090 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001091 }
1092
Zi Wang0a8a1292022-08-30 06:27:01 +00001093 // an intermediate attribute that holds Header_libs info, and will be appended to
1094 // implementationDeps at the end, to solve the confliction that both header_libs
1095 // and static_libs use implementationDeps.
1096 var headerDeps bazel.LabelListAttribute
1097
Liz Kammer47535c52021-06-02 16:02:22 -04001098 productVarToDepFields := map[string]productVarDep{
1099 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001100 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1101 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1102 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001103 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001104 }
1105
Liz Kammer47535c52021-06-02 16:02:22 -04001106 for name, dep := range productVarToDepFields {
1107 props, exists := productVariableProps[name]
1108 excludeProps, excludesExists := productVariableProps[dep.excludesField]
1109 // if neither an include or excludes property exists, then skip it
1110 if !exists && !excludesExists {
1111 continue
1112 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001113 // Collect all the configurations that an include or exclude property exists for.
1114 // We want to iterate all configurations rather than either the include or exclude because, for a
1115 // particular configuration, we may have either only an include or an exclude to handle.
1116 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
1117 for p := range props {
1118 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001119 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001120 for p := range excludeProps {
1121 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001122 }
1123
Jingwen Chen25825ca2021-11-15 12:28:43 +00001124 for productConfigProp := range productConfigProps {
1125 prop, includesExists := props[productConfigProp]
1126 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001127 var includes, excludes []string
1128 var ok bool
1129 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001130 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001131 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1132 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001133 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001134 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1135 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001136
Jingwen Chen58ff6802021-11-17 12:14:41 +00001137 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001138 dep.attribute.SetSelectValue(
1139 productConfigProp.ConfigurationAxis(),
1140 productConfigProp.SelectKey(),
1141 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1142 )
Liz Kammer47535c52021-06-02 16:02:22 -04001143 }
1144 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001145 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001146}
Liz Kammer47535c52021-06-02 16:02:22 -04001147
Liz Kammer54309532021-12-14 12:21:22 -05001148func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1149 // if system dynamic deps have the default value, any use of a system dynamic library used will
1150 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001151 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001152 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
1153 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001154 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001155 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1156 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001157 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001158 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1159 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001160
1161 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
1162 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, toRemove)
1163 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1164 for _, lib := range toRemove.Includes {
1165 lib.Label += stubsSuffix
1166 stubsToRemove = append(stubsToRemove, lib)
1167 }
1168 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001169 }
1170
Liz Kammere6583482021-10-19 13:56:10 -04001171 la.deps.ResolveExcludes()
1172 la.implementationDeps.ResolveExcludes()
1173 la.dynamicDeps.ResolveExcludes()
1174 la.implementationDynamicDeps.ResolveExcludes()
1175 la.wholeArchiveDeps.ResolveExcludes()
1176 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001177
Jingwen Chen91220d72021-03-24 02:18:33 -04001178}
1179
Jingwen Chened9c17d2021-04-13 07:14:55 +00001180// Relativize a list of root-relative paths with respect to the module's
1181// directory.
1182//
1183// include_dirs Soong prop are root-relative (b/183742505), but
1184// local_include_dirs, export_include_dirs and export_system_include_dirs are
1185// module dir relative. This function makes a list of paths entirely module dir
1186// relative.
1187//
1188// For the `include` attribute, Bazel wants the paths to be relative to the
1189// module.
1190func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001191 var relativePaths []string
1192 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001193 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1194 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1195 if err != nil {
1196 panic(err)
1197 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001198 relativePaths = append(relativePaths, relativePath)
1199 }
1200 return relativePaths
1201}
1202
Liz Kammer5fad5012021-09-09 14:08:21 -04001203// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1204// attributes.
1205type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001206 AbsoluteIncludes bazel.StringListAttribute
1207 Includes bazel.StringListAttribute
1208 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001209}
1210
Liz Kammer54549442022-05-11 13:55:06 -04001211func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001212 var exported BazelIncludes
1213 if includes != nil {
1214 exported = *includes
1215 } else {
1216 exported = BazelIncludes{}
1217 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001218 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1219 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1220 if len(flagExporterProperties.Export_include_dirs) > 0 {
1221 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1222 }
1223 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1224 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 -04001225 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001226 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001227 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001228 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001229 exported.Includes.DeduplicateAxesFromBase()
1230 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001231
Liz Kammer5fad5012021-09-09 14:08:21 -04001232 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001233}
Chris Parsons953b3562021-09-20 15:14:39 -04001234
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001235func BazelLabelNameForStaticModule(baseLabel string) string {
1236 return baseLabel + "_bp2build_cc_library_static"
1237}
1238
Jingwen Chen55bc8202021-11-02 06:40:51 +00001239func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001240 label := android.BazelModuleLabel(ctx, m)
Chris Parsonsad876012022-08-20 14:48:32 -04001241 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GetBp2BuildAllowList().GenerateCcLibraryStaticOnly(m.Name()) {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001242 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001243 }
1244 return label
1245}
1246
Jingwen Chen55bc8202021-11-02 06:40:51 +00001247func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001248 // cc_library, at it's root name, propagates the shared library, which depends on the static
1249 // library.
1250 return android.BazelModuleLabel(ctx, m)
1251}
1252
Jingwen Chen55bc8202021-11-02 06:40:51 +00001253func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001254 label := bazelLabelForStaticModule(ctx, m)
1255 if aModule, ok := m.(android.Module); ok {
1256 if android.IsModulePrebuilt(aModule) {
1257 label += "_alwayslink"
1258 }
1259 }
1260 return label
1261}
1262
Jingwen Chen55bc8202021-11-02 06:40:51 +00001263func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001264 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1265}
1266
Jingwen Chen55bc8202021-11-02 06:40:51 +00001267func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001268 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1269}
1270
Jingwen Chen55bc8202021-11-02 06:40:51 +00001271func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001272 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1273}
1274
Jingwen Chen55bc8202021-11-02 06:40:51 +00001275func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001276 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1277}
1278
Jingwen Chen55bc8202021-11-02 06:40:51 +00001279func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001280 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1281}
1282
Jingwen Chen55bc8202021-11-02 06:40:51 +00001283func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001284 // This is not elegant, but bp2build's shared library targets only propagate
1285 // their header information as part of the normal C++ provider.
1286 return bazelLabelForSharedDeps(ctx, modules)
1287}
1288
Zi Wang0a8a1292022-08-30 06:27:01 +00001289func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1290 // This is only used when product_variable header_libs is processed, to follow
1291 // the pattern of depResolutionFunc
1292 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1293}
1294
Jingwen Chen55bc8202021-11-02 06:40:51 +00001295func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001296 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1297}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001298
1299type binaryLinkerAttrs struct {
1300 Linkshared *bool
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001301 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001302}
1303
Jingwen Chen55bc8202021-11-02 06:40:51 +00001304func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001305 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001306 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1307 linkerProps := props.(*BinaryLinkerProperties)
1308 staticExecutable := linkerProps.Static_executable
1309 if axis == bazel.NoConfigAxis {
1310 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1311 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001312 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001313 } else if staticExecutable != nil {
1314 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1315 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1316 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001317 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001318 if suffix := linkerProps.Suffix; suffix != nil {
1319 attrs.Suffix.SetSelectValue(axis, config, suffix)
1320 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001321 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001322
1323 return attrs
1324}