blob: 07e3d7f164f98c6914ad33fdb3e67580a4694a8e [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
Sam Delmericofb3bb322022-10-21 10:42:24 -040069
70 tidyAttributes
71}
72
73type tidyAttributes struct {
74 Tidy *bool
75 Tidy_flags []string
76 Tidy_checks []string
77 Tidy_checks_as_errors []string
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040078 Tidy_disabled_srcs bazel.LabelListAttribute
79 // TODO(b/255754964) support Tidy_timeout_srcs
Sam Delmericofb3bb322022-10-21 10:42:24 -040080}
81
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040082func (m *Module) convertTidyAttributes(ctx android.BaseMutatorContext, moduleAttrs *tidyAttributes) {
Sam Delmericofb3bb322022-10-21 10:42:24 -040083 for _, f := range m.features {
84 if tidy, ok := f.(*tidyFeature); ok {
85 moduleAttrs.Tidy = tidy.Properties.Tidy
86 moduleAttrs.Tidy_flags = tidy.Properties.Tidy_flags
87 moduleAttrs.Tidy_checks = tidy.Properties.Tidy_checks
88 moduleAttrs.Tidy_checks_as_errors = tidy.Properties.Tidy_checks_as_errors
89 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040090
91 }
92
93 archVariantProps := m.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
94 for axis, configToProps := range archVariantProps {
95 for config, _props := range configToProps {
96 if archProps, ok := _props.(*BaseCompilerProperties); ok {
97 archDisabledSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_disabled_srcs)
98 moduleAttrs.Tidy_disabled_srcs.SetSelectValue(axis, config, archDisabledSrcs)
99 }
100 }
Sam Delmericofb3bb322022-10-21 10:42:24 -0400101 }
Jingwen Chen53681ef2021-04-29 08:15:13 +0000102}
103
Sam Delmericoc7681022022-02-04 21:01:20 +0000104// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000105func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400106 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
107 // macro.
108 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -0400109 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
110
111 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -0400112 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -0400113 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
114 return labelStr, false
115 }
Yu Liu2aa806b2022-09-01 11:54:47 -0700116 // If the filegroup is already converted to aidl_library or proto_library,
117 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
118 fg, _ := m.(android.FileGroupAsLibrary)
119 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -0400120 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000121 }
Liz Kammer12615db2021-09-28 09:19:17 -0400122 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400123 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000124 }
125
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400126 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +0000127 labels := bazel.LabelPartitions{
128 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500129 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
130 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -0700131 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -0400132 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000133 // TODO(http://b/231968910): If there is ever a filegroup target that
134 // contains .l or .ll files we will need to find a way to add a
135 // LabelMapper for these that identifies these filegroups and
136 // converts them appropriately
137 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
138 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400139 // C++ is the "catch-all" group, and comprises generated sources because we don't
140 // know the language of these sources until the genrule is executed.
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000141 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
142 syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
Sam Delmericoc7681022022-02-04 21:01:20 +0000143 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000144
Sam Delmericoc7681022022-02-04 21:01:20 +0000145 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000146}
147
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000148// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000149func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000150 lib, ok := module.compiler.(*libraryDecorator)
151 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400152 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000153 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000154 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
155}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000156
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000157// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000158func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000159 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000160}
161
162// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000163func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000164 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400165}
166
Liz Kammer7a210ac2021-09-22 15:52:58 -0400167type depsPartition struct {
168 export bazel.LabelList
169 implementation bazel.LabelList
170}
171
Jingwen Chen55bc8202021-11-02 06:40:51 +0000172type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400173
Jingwen Chen55bc8202021-11-02 06:40:51 +0000174func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400175 if !exportsDeps {
176 return depsPartition{
177 implementation: fn(ctx, allDeps),
178 }
179 }
180
Liz Kammer7a210ac2021-09-22 15:52:58 -0400181 implementation, export := android.FilterList(allDeps, exportedDeps)
182
183 return depsPartition{
184 export: fn(ctx, export),
185 implementation: fn(ctx, implementation),
186 }
187}
188
Jingwen Chen55bc8202021-11-02 06:40:51 +0000189type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400190
Jingwen Chen55bc8202021-11-02 06:40:51 +0000191func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400192 if !exportsDeps {
193 return depsPartition{
194 implementation: fn(ctx, allDeps, excludes),
195 }
196 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400197 implementation, export := android.FilterList(allDeps, exportedDeps)
198
199 return depsPartition{
200 export: fn(ctx, export, excludes),
201 implementation: fn(ctx, implementation, excludes),
202 }
203}
204
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000205func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
206 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
207 for config, props := range configToProps {
208 parseFunc(axis, config, props)
209 }
210 }
211}
212
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000213// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000214func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400215 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000216
Liz Kammer9abd62d2021-05-21 08:37:59 -0400217 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000218 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000219 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400220 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400221
Liz Kammer2b8004b2021-10-04 13:55:44 -0400222 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400223 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
224 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
225
Liz Kammer2b8004b2021-10-04 13:55:44 -0400226 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400227 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
228 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
229
230 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500231 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000232 }
Liz Kammer135bf552021-08-11 10:46:06 -0400233 // system_dynamic_deps distinguishes between nil/empty list behavior:
234 // nil -> use default values
235 // empty list -> no values specified
236 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000237
238 if isStatic {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000239 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
240 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
241 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000242 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000243 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000244 } else {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000245 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
246 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
247 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000248 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000249 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000250 }
251
Liz Kammerae3994e2021-10-19 09:45:48 -0400252 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
253 attrs.Srcs = partitionedSrcs[cppSrcPartition]
254 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
255 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000256
Liz Kammer12615db2021-09-28 09:19:17 -0400257 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
258 // TODO(b/208815215): determine whether this is used and add support if necessary
259 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
260 }
261
Jingwen Chenbcf53042021-05-26 04:42:42 +0000262 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000263}
264
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400265// Convenience struct to hold all attributes parsed from prebuilt properties.
266type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000267 Src bazel.LabelAttribute
268 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400269}
270
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000271func parseSrc(ctx android.BazelConversionPathContext, srcLabelAttribute *bazel.LabelAttribute, axis bazel.ConfigurationAxis, config string, srcs []string) {
272 srcFileError := func() {
273 ctx.ModuleErrorf("parseSrc: Expected at most one source file for %s %s\n", axis, config)
274 }
275 if len(srcs) > 1 {
276 srcFileError()
277 return
278 } else if len(srcs) == 0 {
279 return
280 }
281 if srcLabelAttribute.SelectValue(axis, config) != nil {
282 srcFileError()
283 return
284 }
285 srcLabelAttribute.SetSelectValue(axis, config, android.BazelLabelForModuleSrcSingle(ctx, srcs[0]))
286}
287
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000288// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000289func Bp2BuildParsePrebuiltLibraryProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) prebuiltAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000290
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400291 var srcLabelAttribute bazel.LabelAttribute
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000292 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
293 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000294 parseSrc(ctx, &srcLabelAttribute, axis, config, prebuiltLinkerProperties.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000295 }
296 })
297
298 var enabledLabelAttribute bazel.BoolAttribute
299 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
300 if props.Enabled != nil {
301 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
302 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000303 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000304 }
305
306 if isStatic {
307 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
308 if staticProperties, ok := props.(*StaticProperties); ok {
309 parseAttrs(axis, config, staticProperties.Static)
310 }
311 })
312 } else {
313 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
314 if sharedProperties, ok := props.(*SharedProperties); ok {
315 parseAttrs(axis, config, sharedProperties.Shared)
316 }
317 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400318 }
319
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400320 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000321 Src: srcLabelAttribute,
322 Enabled: enabledLabelAttribute,
323 }
324}
325
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000326func bp2BuildParsePrebuiltBinaryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
327 var srcLabelAttribute bazel.LabelAttribute
328 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
329 if props, ok := props.(*prebuiltLinkerProperties); ok {
330 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000331 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000332 })
333
334 return prebuiltAttributes{
335 Src: srcLabelAttribute,
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400336 }
337}
338
Liz Kammere6583482021-10-19 13:56:10 -0400339type baseAttributes struct {
340 compilerAttributes
341 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400342
Cole Faust5fa4e962022-08-22 14:31:04 -0700343 // A combination of compilerAttributes.features and linkerAttributes.features
344 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400345 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400346 aidlDependency *bazel.LabelAttribute
Liz Kammere6583482021-10-19 13:56:10 -0400347}
348
Jingwen Chen107c0de2021-04-09 10:43:12 +0000349// Convenience struct to hold all attributes parsed from compiler properties.
350type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400351 // Options for all languages
352 copts bazel.StringListAttribute
353 // Assembly options and sources
354 asFlags bazel.StringListAttribute
355 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700356 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400357 // C options and sources
358 conlyFlags bazel.StringListAttribute
359 cSrcs bazel.LabelListAttribute
360 // C++ options and sources
361 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000362 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400363
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000364 // Lex sources and options
365 lSrcs bazel.LabelListAttribute
366 llSrcs bazel.LabelListAttribute
367 lexopts bazel.StringListAttribute
368
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000369 // Sysprop sources
370 syspropSrcs bazel.LabelListAttribute
371
Liz Kammere6583482021-10-19 13:56:10 -0400372 hdrs bazel.LabelListAttribute
373
Chris Parsons2c788392021-08-10 11:58:07 -0400374 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000375
376 // Not affected by arch variants
377 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500378 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000379 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400380
381 localIncludes bazel.StringListAttribute
382 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400383
Liz Kammer1263d9b2021-12-10 14:28:20 -0500384 includes BazelIncludes
385
Liz Kammer12615db2021-09-28 09:19:17 -0400386 protoSrcs bazel.LabelListAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400387 aidlSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000388
389 stubsSymbolFile *string
390 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700391
392 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500393
394 suffix bazel.StringAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000395}
396
Liz Kammercac7f692021-12-16 14:19:32 -0500397type filterOutFn func(string) bool
398
399func filterOutStdFlag(flag string) bool {
400 return strings.HasPrefix(flag, "-std=")
401}
402
Alix1be00d42022-05-16 22:56:04 +0000403func filterOutClangUnknownCflags(flag string) bool {
404 for _, f := range config.ClangUnknownCflags {
405 if f == flag {
406 return true
407 }
408 }
409 return false
410}
411
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000412func parseCommandLineFlags(soongFlags []string, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400413 var result []string
414 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000415 skipFlag := false
416 for _, filter := range filterOut {
417 if filter != nil && filter(flag) {
418 skipFlag = true
419 }
420 }
421 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500422 continue
423 }
Liz Kammere6583482021-10-19 13:56:10 -0400424 // Soong's cflags can contain spaces, like `-include header.h`. For
425 // Bazel's copts, split them up to be compatible with the
426 // no_copts_tokenization feature.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000427 result = append(result, strings.Split(flag, " ")...)
Liz Kammere6583482021-10-19 13:56:10 -0400428 }
429 return result
430}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000431
Jingwen Chen55bc8202021-11-02 06:40:51 +0000432func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400433 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
434 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
435 if srcsList, ok := parseSrcs(ctx, props); ok {
436 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400437 }
438
Liz Kammere6583482021-10-19 13:56:10 -0400439 localIncludeDirs := props.Local_include_dirs
440 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500441 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400442 if includeBuildDirectory(props.Include_build_directory) {
443 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400444 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000445 }
446
Liz Kammere6583482021-10-19 13:56:10 -0400447 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
448 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
449
Cole Faust5fa4e962022-08-22 14:31:04 -0700450 instructionSet := proptools.StringDefault(props.Instruction_set, "")
451 if instructionSet == "arm" {
452 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm", "-arm_isa_thumb"})
453 } else if instructionSet != "" && instructionSet != "thumb" {
454 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
455 }
456
Liz Kammercac7f692021-12-16 14:19:32 -0500457 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
458 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
459 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
460 // cases.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000461 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutClangUnknownCflags))
462 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
463 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, filterOutClangUnknownCflags))
464 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400465 ca.rtti.SetSelectValue(axis, config, props.Rtti)
466}
467
Jingwen Chen55bc8202021-11-02 06:40:51 +0000468func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000469 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
470 if stlProps, ok := props.(*StlProperties); ok {
471 if stlProps.Stl == nil {
472 return
473 }
474 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400475 stl := deduplicateStlInput(*stlProps.Stl)
476 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000477 } else if ca.stl != stlProps.Stl {
478 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 -0400479 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000480 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000481 })
Liz Kammere6583482021-10-19 13:56:10 -0400482}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000483
Jingwen Chen55bc8202021-11-02 06:40:51 +0000484func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400485 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400486 "Cflags": &ca.copts,
487 "Asflags": &ca.asFlags,
488 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400489 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400490 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000491 if productConfigProps, exists := productVariableProps[propName]; exists {
492 for productConfigProp, prop := range productConfigProps {
493 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400494 if !ok {
495 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
496 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000497 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
498 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400499 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400500 }
501 }
Liz Kammere6583482021-10-19 13:56:10 -0400502}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400503
Jingwen Chen55bc8202021-11-02 06:40:51 +0000504func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400505 ca.srcs.ResolveExcludes()
506 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
507
Liz Kammer12615db2021-09-28 09:19:17 -0400508 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400509 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400510
Liz Kammere6583482021-10-19 13:56:10 -0400511 for p, lla := range partitionedSrcs {
512 // if there are no sources, there is no need for headers
513 if lla.IsEmpty() {
514 continue
515 }
516 lla.Append(implementationHdrs)
517 partitionedSrcs[p] = lla
518 }
519
520 ca.srcs = partitionedSrcs[cppSrcPartition]
521 ca.cSrcs = partitionedSrcs[cSrcPartition]
522 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700523 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000524 ca.lSrcs = partitionedSrcs[lSrcPartition]
525 ca.llSrcs = partitionedSrcs[llSrcPartition]
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000526 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400527
528 ca.absoluteIncludes.DeduplicateAxesFromBase()
529 ca.localIncludes.DeduplicateAxesFromBase()
530}
531
532// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000533func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400534 anySrcs := false
535 // Add srcs-like dependencies such as generated files.
536 // First create a LabelList containing these dependencies, then merge the values with srcs.
537 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
538 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
539 anySrcs = true
540 }
541
542 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400543
Liz Kammere6583482021-10-19 13:56:10 -0400544 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
545 anySrcs = true
546 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400547
Liz Kammere6583482021-10-19 13:56:10 -0400548 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
549}
550
Liz Kammera5a29de2022-05-25 23:19:37 -0400551func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
552 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500553 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
554 // Defaults are handled by the toolchain definition.
555 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400556 stdVal := proptools.StringDefault(std, defaultVal)
557 if stdVal == "experimental" || stdVal == defaultVal {
558 if stdVal == "experimental" {
559 stdVal = prefix + "_std_experimental"
560 }
561 if !useGnu {
562 stdVal += "_no_gnu"
563 }
564 } else if !useGnu {
565 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500566 }
567
Liz Kammera5a29de2022-05-25 23:19:37 -0400568 if stdVal == defaultVal {
569 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500570 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400571 return &stdVal
572}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500573
Liz Kammera5a29de2022-05-25 23:19:37 -0400574func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
575 useGnu := useGnuExtensions(gnu_extensions)
576
577 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400578}
579
Liz Kammer1263d9b2021-12-10 14:28:20 -0500580// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
581// is fully-qualified.
582// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
583func packageFromLabel(label string) (string, bool) {
584 split := strings.Split(label, ":")
585 if len(split) != 2 {
586 return "", false
587 }
588 if split[0] == "" {
589 return ".", false
590 }
591 // remove leading "//"
592 return split[0][2:], true
593}
594
595// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
596func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
597 for _, hdr := range labelList.Includes {
598 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
599 absolute = append(absolute, pkg)
600 } else if pkg != "" {
601 relative = append(relative, pkg)
602 }
603 }
604 return relative, absolute
605}
606
Cole Faust7071a052022-07-29 15:58:33 -0700607type YasmAttributes struct {
608 Srcs bazel.LabelListAttribute
609 Flags bazel.StringListAttribute
610 Include_dirs bazel.StringListAttribute
611}
612
613func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
614 if ca.asmSrcs.IsEmpty() {
615 return nil
616 }
617
618 // Yasm needs the include directories from both local_includes and
619 // export_include_dirs. We don't care about actually exporting them from the
620 // yasm rule though, because they will also be present on the cc_ rule that
621 // wraps this yasm rule.
622 includes := ca.localIncludes.Clone()
623 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
624 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
625 if len(flagExporterProperties.Export_include_dirs) > 0 {
626 x := bazel.StringListAttribute{}
627 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
628 includes.Append(x)
629 }
630 }
631 })
632
633 ctx.CreateBazelTargetModule(
634 bazel.BazelTargetModuleProperties{
635 Rule_class: "yasm",
636 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
637 },
638 android.CommonAttributes{Name: m.Name() + "_yasm"},
639 &YasmAttributes{
640 Srcs: ca.asmSrcs,
641 Flags: ca.asFlags,
642 Include_dirs: *includes,
643 })
644
645 // We only want to add a dependency on the _yasm target if there are asm
646 // sources in the current configuration. If there are unconfigured asm
647 // sources, always add the dependency. Otherwise, add the dependency only
648 // on the configuration axes and values that had asm sources.
649 if len(ca.asmSrcs.Value.Includes) > 0 {
650 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
651 }
652
653 ret := &bazel.LabelAttribute{}
654 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
655 for config := range ca.asmSrcs.ConfigurableValues[axis] {
656 ret.SetSelectValue(axis, config, bazel.Label{Label: ":" + m.Name() + "_yasm"})
657 }
658 }
659 return ret
660}
661
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000662// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400663func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400664 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
665 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000666 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400667
668 var implementationHdrs bazel.LabelListAttribute
669
670 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
671 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
672 for axis, configMap := range cp {
673 if _, ok := axisToConfigs[axis]; !ok {
674 axisToConfigs[axis] = map[string]bool{}
675 }
676 for config, _ := range configMap {
677 axisToConfigs[axis][config] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400678 }
679 }
680 }
Liz Kammere6583482021-10-19 13:56:10 -0400681 allAxesAndConfigs(archVariantCompilerProps)
682 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000683 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400684
Liz Kammere6583482021-10-19 13:56:10 -0400685 compilerAttrs := compilerAttributes{}
686 linkerAttrs := linkerAttributes{}
687
688 for axis, configs := range axisToConfigs {
689 for config, _ := range configs {
690 var allHdrs []string
691 if baseCompilerProps, ok := archVariantCompilerProps[axis][config].(*BaseCompilerProperties); ok {
692 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000693 if baseCompilerProps.Lex != nil {
694 compilerAttrs.lexopts.SetSelectValue(axis, config, baseCompilerProps.Lex.Flags)
695 }
Liz Kammere6583482021-10-19 13:56:10 -0400696 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, config, baseCompilerProps)
697 }
698
699 var exportHdrs []string
700
701 if baseLinkerProps, ok := archVariantLinkerProps[axis][config].(*BaseLinkerProperties); ok {
702 exportHdrs = baseLinkerProps.Export_generated_headers
703
704 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module.Binary(), axis, config, baseLinkerProps)
705 }
706 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
707 implementationHdrs.SetSelectValue(axis, config, headers.implementation)
708 compilerAttrs.hdrs.SetSelectValue(axis, config, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500709
710 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
711 compilerAttrs.includes.Includes.SetSelectValue(axis, config, exportIncludes)
712 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, config, exportAbsoluteIncludes)
713
714 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
715 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, config)
716 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400717
Liz Kammer1263d9b2021-12-10 14:28:20 -0500718 compilerAttrs.absoluteIncludes.SetSelectValue(axis, config, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400719
Liz Kammer1263d9b2021-12-10 14:28:20 -0500720 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, config)
721 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400722
Liz Kammer1263d9b2021-12-10 14:28:20 -0500723 compilerAttrs.localIncludes.SetSelectValue(axis, config, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000724
725 if libraryProps, ok := archVariantLibraryProperties[axis][config].(*LibraryProperties); ok {
726 if axis == bazel.NoConfigAxis {
727 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
728 compilerAttrs.stubsVersions.SetSelectValue(axis, config, libraryProps.Stubs.Versions)
729 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500730 if suffix := libraryProps.Suffix; suffix != nil {
731 compilerAttrs.suffix.SetSelectValue(axis, config, suffix)
732 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000733 }
Liz Kammere6583482021-10-19 13:56:10 -0400734 }
735 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400736
Liz Kammere6583482021-10-19 13:56:10 -0400737 compilerAttrs.convertStlProps(ctx, module)
738 (&linkerAttrs).convertStripProps(ctx, module)
739
Yu Liu8d82ac52022-05-17 15:13:28 -0700740 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
741 !Bool(module.coverage.Properties.Native_coverage) {
742 // Native_coverage is arch neutral
743 (&linkerAttrs).features.Append(bazel.MakeStringListAttribute([]string{"-coverage"}))
744 }
745
Liz Kammere6583482021-10-19 13:56:10 -0400746 productVariableProps := android.ProductVariableProperties(ctx)
747
748 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
749 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
750
751 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500752 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400753
Cole Faust7071a052022-07-29 15:58:33 -0700754 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
755
Liz Kammer12615db2021-09-28 09:19:17 -0400756 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
757
758 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
759 // which. This will add the newly generated proto library to the appropriate attribute and nothing
760 // to the other
761 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
762 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400763
Vinh Tran395a1e92022-09-16 18:27:29 -0400764 aidlDep := bp2buildCcAidlLibrary(ctx, module, compilerAttrs.aidlSrcs, linkerAttrs)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400765 if aidlDep != nil {
766 if lib, ok := module.linker.(*libraryDecorator); ok {
767 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
768 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
769 } else {
770 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
771 }
772 }
773 }
Liz Kammer12615db2021-09-28 09:19:17 -0400774
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000775 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
776 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
777 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
778
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000779 if !compilerAttrs.syspropSrcs.IsEmpty() {
780 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
781 }
782
Cole Faust5fa4e962022-08-22 14:31:04 -0700783 features := compilerAttrs.features.Clone().Append(linkerAttrs.features)
784 features.DeduplicateAxesFromBase()
785
Liz Kammere6583482021-10-19 13:56:10 -0400786 return baseAttributes{
787 compilerAttrs,
788 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700789 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400790 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400791 aidlDep,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000792 }
793}
794
Vinh Tran9f6796a2022-08-16 13:10:31 -0400795func bp2buildCcAidlLibrary(
796 ctx android.Bp2buildMutatorContext,
797 m *Module,
Vinh Trana3b8b782022-09-14 11:40:24 -0400798 aidlLabelList bazel.LabelListAttribute,
Vinh Tran395a1e92022-09-16 18:27:29 -0400799 linkerAttrs linkerAttributes,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400800) *bazel.LabelAttribute {
Vinh Trana3b8b782022-09-14 11:40:24 -0400801 if !aidlLabelList.IsEmpty() {
802 aidlLibs, aidlSrcs := aidlLabelList.Partition(func(src bazel.Label) bool {
803 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
804 fg.ShouldConvertToAidlLibrary(ctx) {
805 return true
806 }
807 return false
808 })
Vinh Tran9f6796a2022-08-16 13:10:31 -0400809
Vinh Trana3b8b782022-09-14 11:40:24 -0400810 if !aidlSrcs.IsEmpty() {
811 aidlLibName := m.Name() + "_aidl_library"
812 ctx.CreateBazelTargetModule(
813 bazel.BazelTargetModuleProperties{
814 Rule_class: "aidl_library",
815 Bzl_load_location: "//build/bazel/rules/aidl:library.bzl",
816 },
817 android.CommonAttributes{Name: aidlLibName},
818 &aidlLibraryAttributes{
819 Srcs: aidlSrcs,
820 },
821 )
822 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
823 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400824
Vinh Trana3b8b782022-09-14 11:40:24 -0400825 if !aidlLibs.IsEmpty() {
826 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
Vinh Tran395a1e92022-09-16 18:27:29 -0400827 // Since cc_aidl_library only needs the dynamic deps (aka shared libs) from the parent cc library for compiling,
828 // we err on the side of not re-exporting the headers of the dynamic deps from cc_aidl_lirary
829 // because the parent cc library already has all the dynamic deps
830 implementationDynamicDeps := bazel.MakeLabelListAttribute(
831 bazel.AppendBazelLabelLists(
832 linkerAttrs.dynamicDeps.Value,
833 linkerAttrs.implementationDynamicDeps.Value,
834 ),
835 )
836
Vinh Trana3b8b782022-09-14 11:40:24 -0400837 ctx.CreateBazelTargetModule(
838 bazel.BazelTargetModuleProperties{
839 Rule_class: "cc_aidl_library",
840 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
841 },
842 android.CommonAttributes{Name: ccAidlLibrarylabel},
843 &ccAidlLibraryAttributes{
Vinh Tran395a1e92022-09-16 18:27:29 -0400844 Deps: aidlLibs,
845 Implementation_dynamic_deps: implementationDynamicDeps,
Vinh Trana3b8b782022-09-14 11:40:24 -0400846 },
847 )
848 label := &bazel.LabelAttribute{
849 Value: &bazel.Label{
850 Label: ":" + ccAidlLibrarylabel,
851 },
852 }
853 return label
854 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400855 }
856
Vinh Trana3b8b782022-09-14 11:40:24 -0400857 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -0400858}
859
Yu Liufc603162022-03-01 15:44:08 -0800860func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000861 return sdkAttributes{
862 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800863 Min_sdk_version: module.Properties.Min_sdk_version,
864 }
865}
866
867type sdkAttributes struct {
868 Sdk_version *string
869 Min_sdk_version *string
870}
871
Jingwen Chen107c0de2021-04-09 10:43:12 +0000872// Convenience struct to hold all attributes parsed from linker properties.
873type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500874 deps bazel.LabelListAttribute
875 implementationDeps bazel.LabelListAttribute
876 dynamicDeps bazel.LabelListAttribute
877 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -0700878 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -0500879 wholeArchiveDeps bazel.LabelListAttribute
880 implementationWholeArchiveDeps bazel.LabelListAttribute
881 systemDynamicDeps bazel.LabelListAttribute
882 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400883
Jingwen Chen6ada5892021-09-17 11:38:09 +0000884 linkCrt bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000885 useLibcrt bazel.BoolAttribute
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500886 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000887 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -0400888 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000889 stripKeepSymbols bazel.BoolAttribute
890 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
891 stripKeepSymbolsList bazel.StringListAttribute
892 stripAll bazel.BoolAttribute
893 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -0400894 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -0400895}
896
Liz Kammer54309532021-12-14 12:21:22 -0500897var (
898 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -0400899 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -0500900)
901
Vinh Tran85fb07c2022-09-16 16:17:48 -0400902// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
903// since all libs are already excluded by default
904func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, isBinary bool, props *BaseLinkerProperties) {
905 sharedLibsForNonApex := maybePartitionExportedAndImplementationsDeps(
906 ctx,
907 true,
908 props.Target.Apex.Exclude_shared_libs,
909 props.Export_shared_lib_headers,
910 bazelLabelForSharedDeps,
911 )
912 dynamicDeps := la.dynamicDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
913 implDynamicDeps := la.implementationDynamicDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
914 (&dynamicDeps).Append(sharedLibsForNonApex.export)
915 (&implDynamicDeps).Append(sharedLibsForNonApex.implementation)
916 la.dynamicDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, dynamicDeps)
917 la.implementationDynamicDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, implDynamicDeps)
918
919 staticLibsForNonApex := maybePartitionExportedAndImplementationsDeps(
920 ctx,
921 !isBinary,
922 props.Target.Apex.Exclude_static_libs,
923 props.Export_static_lib_headers,
924 bazelLabelForSharedDeps,
925 )
926 deps := la.deps.SelectValue(bazel.InApexAxis, bazel.NonApex)
927 implDeps := la.implementationDeps.SelectValue(bazel.InApexAxis, bazel.NonApex)
928 (&deps).Append(staticLibsForNonApex.export)
929 (&implDeps).Append(staticLibsForNonApex.implementation)
930 la.deps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, deps)
931 la.implementationDeps.SetSelectValue(bazel.InApexAxis, bazel.NonApex, implDeps)
932}
933
Jingwen Chen55bc8202021-11-02 06:40:51 +0000934func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, isBinary bool, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400935 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
936 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -0400937
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400938 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -0400939 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
940 if axis == bazel.NoConfigAxis {
941 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
942 if proptools.Bool(props.Use_version_lib) {
943 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
944 // remove from static libs so there is no duplicate dependency
945 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
946 // only add the dep if it is not in progress
947 if !versionLibAlreadyInDeps {
948 if isBinary {
949 wholeStaticLibs = append(wholeStaticLibs, versionLib)
950 } else {
951 la.implementationWholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, []string{versionLib}, props.Exclude_static_libs))
952 }
953 }
954 }
955 }
956
Liz Kammere6583482021-10-19 13:56:10 -0400957 // Excludes to parallel Soong:
958 // 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 -0400959 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -0400960
Vinh Tran85fb07c2022-09-16 16:17:48 -0400961 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
962 ctx,
963 !isBinary,
964 staticLibs,
965 // Exclude static libs in Exclude_static_libs and Target.Apex.Exclude_static_libs props
966 append(props.Exclude_static_libs, props.Target.Apex.Exclude_static_libs...),
967 props.Export_static_lib_headers,
968 bazelLabelForStaticDepsExcludes,
969 )
Liz Kammer7a210ac2021-09-22 15:52:58 -0400970
Liz Kammere6583482021-10-19 13:56:10 -0400971 headerLibs := android.FirstUniqueStrings(props.Header_libs)
972 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -0400973
Liz Kammere6583482021-10-19 13:56:10 -0400974 (&hDeps.export).Append(staticDeps.export)
975 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +0000976
Liz Kammere6583482021-10-19 13:56:10 -0400977 (&hDeps.implementation).Append(staticDeps.implementation)
978 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -0400979
Liz Kammere6583482021-10-19 13:56:10 -0400980 systemSharedLibs := props.System_shared_libs
981 // systemSharedLibs distinguishes between nil/empty list behavior:
982 // nil -> use default values
983 // empty list -> no values specified
984 if len(systemSharedLibs) > 0 {
985 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
986 }
987 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
988
989 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -0500990 excludeSharedLibs := props.Exclude_shared_libs
991 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
992 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
993 })
994 for _, el := range usedSystem {
995 if la.usedSystemDynamicDepAsDynamicDep == nil {
996 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
997 }
998 la.usedSystemDynamicDepAsDynamicDep[el] = true
999 }
1000
Vinh Tran85fb07c2022-09-16 16:17:48 -04001001 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1002 ctx,
1003 !isBinary,
1004 sharedLibs,
1005 // Exclude shared libs in Exclude_shared_libs and Target.Apex.Exclude_shared_libs props
1006 append(props.Exclude_shared_libs, props.Target.Apex.Exclude_shared_libs...),
1007 props.Export_shared_lib_headers,
1008 bazelLabelForSharedDepsExcludes,
1009 )
Liz Kammere6583482021-10-19 13:56:10 -04001010 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
1011 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001012 la.resolveTargetApexProp(ctx, isBinary, props)
1013
Wei Li81852ca2022-07-27 00:22:06 -07001014 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
1015 // If a dependency in la.implementationDynamicDeps has stubs, its stub variant should be
1016 // used when the dependency is linked in a APEX. The dependencies in NoConfigAxis and
1017 // OsConfigurationAxis/OsAndroid are grouped by having stubs or not, so Bazel select()
1018 // statement can be used to choose source/stub variants of them.
1019 depsWithStubs := []bazel.Label{}
1020 for _, l := range sharedDeps.implementation.Includes {
1021 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
1022 if m, ok := dep.(*Module); ok && m.HasStubsVariants() {
1023 depsWithStubs = append(depsWithStubs, l)
1024 }
1025 }
1026 if len(depsWithStubs) > 0 {
1027 implDynamicDeps := bazel.SubtractBazelLabelList(sharedDeps.implementation, bazel.MakeLabelList(depsWithStubs))
1028 la.implementationDynamicDeps.SetSelectValue(axis, config, implDynamicDeps)
1029
1030 stubLibLabels := []bazel.Label{}
1031 for _, l := range depsWithStubs {
Liz Kammer91487d42022-09-13 11:27:11 -04001032 l.Label = l.Label + stubsSuffix
Wei Li81852ca2022-07-27 00:22:06 -07001033 stubLibLabels = append(stubLibLabels, l)
1034 }
1035 inApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex)
1036 nonApexSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex)
1037 defaultSelectValue := la.implementationDynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
1038 if axis == bazel.NoConfigAxis {
1039 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
1040 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
1041 (&defaultSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
Trevor Radcliffe0ed6b7d2022-09-12 20:19:26 +00001042 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1043 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
1044 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
Wei Li81852ca2022-07-27 00:22:06 -07001045 } else if config == bazel.OsAndroid {
1046 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
1047 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
Trevor Radcliffe0ed6b7d2022-09-12 20:19:26 +00001048 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1049 la.implementationDynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
Wei Li81852ca2022-07-27 00:22:06 -07001050 }
1051 }
1052 }
Liz Kammere6583482021-10-19 13:56:10 -04001053
1054 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1055 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1056 }
1057
1058 if Bool(props.Allow_undefined_symbols) {
1059 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1060 }
1061
1062 var linkerFlags []string
1063 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001064 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001065 // binaries remove static flag if -shared is in the linker flags
1066 if isBinary && android.InList("-shared", linkerFlags) {
1067 axisFeatures = append(axisFeatures, "-static_flag")
1068 }
1069 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001070
1071 // This must happen before the addition of flags for Version Script and
1072 // Dynamic List, as these flags must be split on spaces and those must not
1073 linkerFlags = parseCommandLineFlags(linkerFlags, filterOutClangUnknownCflags)
1074
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001075 additionalLinkerInputs := bazel.LabelList{}
Liz Kammere6583482021-10-19 13:56:10 -04001076 if props.Version_script != nil {
1077 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001078 additionalLinkerInputs.Add(&label)
Liz Kammere6583482021-10-19 13:56:10 -04001079 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
1080 }
Alix773adaa2022-04-27 17:49:34 +00001081
1082 if props.Dynamic_list != nil {
1083 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001084 additionalLinkerInputs.Add(&label)
Alix773adaa2022-04-27 17:49:34 +00001085 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1086 }
1087
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001088 la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001089 la.linkopts.SetSelectValue(axis, config, linkerFlags)
Liz Kammere6583482021-10-19 13:56:10 -04001090 la.useLibcrt.SetSelectValue(axis, config, props.libCrt())
1091
1092 // it's very unlikely for nocrt to be arch variant, so bp2build doesn't support it.
1093 if props.crt() != nil {
1094 if axis == bazel.NoConfigAxis {
1095 la.linkCrt.SetSelectValue(axis, config, props.crt())
1096 } else if axis == bazel.ArchConfigurationAxis {
1097 ctx.ModuleErrorf("nocrt is not supported for arch variants")
1098 }
1099 }
1100
1101 if axisFeatures != nil {
1102 la.features.SetSelectValue(axis, config, axisFeatures)
1103 }
Cole Faust6b29f592022-08-09 09:50:56 -07001104
1105 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1106 if !runtimeDeps.IsEmpty() {
1107 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1108 }
Liz Kammere6583482021-10-19 13:56:10 -04001109}
1110
Jingwen Chen55bc8202021-11-02 06:40:51 +00001111func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001112 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1113 if stripProperties, ok := props.(*StripProperties); ok {
1114 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1115 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1116 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1117 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1118 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001119 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001120 })
Liz Kammere6583482021-10-19 13:56:10 -04001121}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001122
Jingwen Chen55bc8202021-11-02 06:40:51 +00001123func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001124
Liz Kammer47535c52021-06-02 16:02:22 -04001125 type productVarDep struct {
1126 // the name of the corresponding excludes field, if one exists
1127 excludesField string
1128 // reference to the bazel attribute that should be set for the given product variable config
1129 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001130
Jingwen Chen55bc8202021-11-02 06:40:51 +00001131 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001132 }
1133
Zi Wang0a8a1292022-08-30 06:27:01 +00001134 // an intermediate attribute that holds Header_libs info, and will be appended to
1135 // implementationDeps at the end, to solve the confliction that both header_libs
1136 // and static_libs use implementationDeps.
1137 var headerDeps bazel.LabelListAttribute
1138
Liz Kammer47535c52021-06-02 16:02:22 -04001139 productVarToDepFields := map[string]productVarDep{
1140 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001141 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1142 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1143 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001144 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001145 }
1146
Liz Kammer47535c52021-06-02 16:02:22 -04001147 for name, dep := range productVarToDepFields {
1148 props, exists := productVariableProps[name]
1149 excludeProps, excludesExists := productVariableProps[dep.excludesField]
1150 // if neither an include or excludes property exists, then skip it
1151 if !exists && !excludesExists {
1152 continue
1153 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001154 // Collect all the configurations that an include or exclude property exists for.
1155 // We want to iterate all configurations rather than either the include or exclude because, for a
1156 // particular configuration, we may have either only an include or an exclude to handle.
1157 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
1158 for p := range props {
1159 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001160 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001161 for p := range excludeProps {
1162 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001163 }
1164
Jingwen Chen25825ca2021-11-15 12:28:43 +00001165 for productConfigProp := range productConfigProps {
1166 prop, includesExists := props[productConfigProp]
1167 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001168 var includes, excludes []string
1169 var ok bool
1170 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001171 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001172 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1173 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001174 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001175 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1176 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001177
Jingwen Chen58ff6802021-11-17 12:14:41 +00001178 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001179 dep.attribute.SetSelectValue(
1180 productConfigProp.ConfigurationAxis(),
1181 productConfigProp.SelectKey(),
1182 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1183 )
Liz Kammer47535c52021-06-02 16:02:22 -04001184 }
1185 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001186 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001187}
Liz Kammer47535c52021-06-02 16:02:22 -04001188
Liz Kammer54309532021-12-14 12:21:22 -05001189func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1190 // if system dynamic deps have the default value, any use of a system dynamic library used will
1191 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001192 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001193 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
1194 toRemove := bazelLabelForSharedDeps(ctx, android.SortedStringKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001195 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001196 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1197 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001198 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001199 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1200 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001201
1202 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
1203 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, toRemove)
1204 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1205 for _, lib := range toRemove.Includes {
1206 lib.Label += stubsSuffix
1207 stubsToRemove = append(stubsToRemove, lib)
1208 }
1209 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001210 }
1211
Liz Kammere6583482021-10-19 13:56:10 -04001212 la.deps.ResolveExcludes()
1213 la.implementationDeps.ResolveExcludes()
1214 la.dynamicDeps.ResolveExcludes()
1215 la.implementationDynamicDeps.ResolveExcludes()
1216 la.wholeArchiveDeps.ResolveExcludes()
1217 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001218
Jingwen Chen91220d72021-03-24 02:18:33 -04001219}
1220
Jingwen Chened9c17d2021-04-13 07:14:55 +00001221// Relativize a list of root-relative paths with respect to the module's
1222// directory.
1223//
1224// include_dirs Soong prop are root-relative (b/183742505), but
1225// local_include_dirs, export_include_dirs and export_system_include_dirs are
1226// module dir relative. This function makes a list of paths entirely module dir
1227// relative.
1228//
1229// For the `include` attribute, Bazel wants the paths to be relative to the
1230// module.
1231func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001232 var relativePaths []string
1233 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001234 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1235 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1236 if err != nil {
1237 panic(err)
1238 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001239 relativePaths = append(relativePaths, relativePath)
1240 }
1241 return relativePaths
1242}
1243
Liz Kammer5fad5012021-09-09 14:08:21 -04001244// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1245// attributes.
1246type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001247 AbsoluteIncludes bazel.StringListAttribute
1248 Includes bazel.StringListAttribute
1249 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001250}
1251
Liz Kammer54549442022-05-11 13:55:06 -04001252func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001253 var exported BazelIncludes
1254 if includes != nil {
1255 exported = *includes
1256 } else {
1257 exported = BazelIncludes{}
1258 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001259 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1260 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1261 if len(flagExporterProperties.Export_include_dirs) > 0 {
1262 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1263 }
1264 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1265 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 -04001266 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001267 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001268 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001269 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001270 exported.Includes.DeduplicateAxesFromBase()
1271 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001272
Liz Kammer5fad5012021-09-09 14:08:21 -04001273 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001274}
Chris Parsons953b3562021-09-20 15:14:39 -04001275
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001276func BazelLabelNameForStaticModule(baseLabel string) string {
1277 return baseLabel + "_bp2build_cc_library_static"
1278}
1279
Jingwen Chen55bc8202021-11-02 06:40:51 +00001280func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001281 label := android.BazelModuleLabel(ctx, m)
Chris Parsonsad876012022-08-20 14:48:32 -04001282 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary && !android.GetBp2BuildAllowList().GenerateCcLibraryStaticOnly(m.Name()) {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001283 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001284 }
1285 return label
1286}
1287
Jingwen Chen55bc8202021-11-02 06:40:51 +00001288func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001289 // cc_library, at it's root name, propagates the shared library, which depends on the static
1290 // library.
1291 return android.BazelModuleLabel(ctx, m)
1292}
1293
Jingwen Chen55bc8202021-11-02 06:40:51 +00001294func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001295 label := bazelLabelForStaticModule(ctx, m)
1296 if aModule, ok := m.(android.Module); ok {
1297 if android.IsModulePrebuilt(aModule) {
1298 label += "_alwayslink"
1299 }
1300 }
1301 return label
1302}
1303
Jingwen Chen55bc8202021-11-02 06:40:51 +00001304func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001305 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1306}
1307
Jingwen Chen55bc8202021-11-02 06:40:51 +00001308func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001309 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1310}
1311
Jingwen Chen55bc8202021-11-02 06:40:51 +00001312func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001313 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1314}
1315
Jingwen Chen55bc8202021-11-02 06:40:51 +00001316func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001317 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1318}
1319
Jingwen Chen55bc8202021-11-02 06:40:51 +00001320func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001321 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1322}
1323
Jingwen Chen55bc8202021-11-02 06:40:51 +00001324func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001325 // This is not elegant, but bp2build's shared library targets only propagate
1326 // their header information as part of the normal C++ provider.
1327 return bazelLabelForSharedDeps(ctx, modules)
1328}
1329
Zi Wang0a8a1292022-08-30 06:27:01 +00001330func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1331 // This is only used when product_variable header_libs is processed, to follow
1332 // the pattern of depResolutionFunc
1333 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1334}
1335
Jingwen Chen55bc8202021-11-02 06:40:51 +00001336func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001337 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1338}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001339
1340type binaryLinkerAttrs struct {
1341 Linkshared *bool
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001342 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001343}
1344
Jingwen Chen55bc8202021-11-02 06:40:51 +00001345func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001346 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001347 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1348 linkerProps := props.(*BinaryLinkerProperties)
1349 staticExecutable := linkerProps.Static_executable
1350 if axis == bazel.NoConfigAxis {
1351 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1352 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001353 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001354 } else if staticExecutable != nil {
1355 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1356 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1357 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001358 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001359 if suffix := linkerProps.Suffix; suffix != nil {
1360 attrs.Suffix.SetSelectValue(axis, config, suffix)
1361 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001362 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001363
1364 return attrs
1365}