blob: feb17b0504dcbd9c102b5fff048cba3b209112fa [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"
Spandan Das4242f102023-04-19 22:31:54 +000020 "sync"
Chris Parsons484e50a2021-05-13 15:13:04 -040021
22 "android/soong/android"
23 "android/soong/bazel"
Alix1be00d42022-05-16 22:56:04 +000024 "android/soong/cc/config"
Liz Kammer7a210ac2021-09-22 15:52:58 -040025
Chris Parsons953b3562021-09-20 15:14:39 -040026 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040027
28 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040029)
30
Liz Kammerae3994e2021-10-19 09:45:48 -040031const (
Trevor Radcliffecee4e052022-09-06 19:31:25 +000032 cSrcPartition = "c"
33 asSrcPartition = "as"
34 asmSrcPartition = "asm"
35 lSrcPartition = "l"
36 llSrcPartition = "ll"
37 cppSrcPartition = "cpp"
38 protoSrcPartition = "proto"
39 aidlSrcPartition = "aidl"
40 syspropSrcPartition = "sysprop"
Spandan Dasdf4c2132023-05-09 23:58:52 +000041 yaccSrcPartition = "yacc"
Liz Kammer91487d42022-09-13 11:27:11 -040042
43 stubsSuffix = "_stub_libs_current"
Liz Kammerae3994e2021-10-19 09:45:48 -040044)
45
Liz Kammer2222c6b2021-05-24 15:41:47 -040046// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000047// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040048type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040049 Srcs bazel.LabelListAttribute
50 Srcs_c bazel.LabelListAttribute
51 Srcs_as bazel.LabelListAttribute
52 Srcs_aidl bazel.LabelListAttribute
53 Hdrs bazel.LabelListAttribute
54 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000055
Liz Kammer12615db2021-09-28 09:19:17 -040056 Deps bazel.LabelListAttribute
57 Implementation_deps bazel.LabelListAttribute
58 Dynamic_deps bazel.LabelListAttribute
59 Implementation_dynamic_deps bazel.LabelListAttribute
60 Whole_archive_deps bazel.LabelListAttribute
61 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070062 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040063
64 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050065
66 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080067
Yu Liuf01a0f02022-12-07 15:45:30 -080068 Native_coverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -070069
Liz Kammeraceec252023-03-24 09:46:36 -040070 Apex_available []string
71
Trevor Radcliffea8b44162023-04-14 18:25:24 +000072 Features bazel.StringListAttribute
73
Yu Liufc603162022-03-01 15:44:08 -080074 sdkAttributes
Sam Delmericofb3bb322022-10-21 10:42:24 -040075
76 tidyAttributes
77}
78
79type tidyAttributes struct {
Sam Delmerico63f0c932023-03-14 14:05:28 -040080 Tidy *string
Sam Delmericofb3bb322022-10-21 10:42:24 -040081 Tidy_flags []string
82 Tidy_checks []string
83 Tidy_checks_as_errors []string
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040084 Tidy_disabled_srcs bazel.LabelListAttribute
Sam Delmerico4c902d62022-11-02 14:17:15 -040085 Tidy_timeout_srcs bazel.LabelListAttribute
Sam Delmericofb3bb322022-10-21 10:42:24 -040086}
87
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040088func (m *Module) convertTidyAttributes(ctx android.BaseMutatorContext, moduleAttrs *tidyAttributes) {
Sam Delmericofb3bb322022-10-21 10:42:24 -040089 for _, f := range m.features {
90 if tidy, ok := f.(*tidyFeature); ok {
Sam Delmerico63f0c932023-03-14 14:05:28 -040091 var tidyAttr *string
92 if tidy.Properties.Tidy != nil {
93 if *tidy.Properties.Tidy {
94 tidyAttr = proptools.StringPtr("local")
95 } else {
96 tidyAttr = proptools.StringPtr("never")
97 }
98 }
99 moduleAttrs.Tidy = tidyAttr
Sam Delmericofb3bb322022-10-21 10:42:24 -0400100 moduleAttrs.Tidy_flags = tidy.Properties.Tidy_flags
101 moduleAttrs.Tidy_checks = tidy.Properties.Tidy_checks
102 moduleAttrs.Tidy_checks_as_errors = tidy.Properties.Tidy_checks_as_errors
103 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400104
105 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400106 archVariantProps := m.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
107 for axis, configToProps := range archVariantProps {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800108 for cfg, _props := range configToProps {
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400109 if archProps, ok := _props.(*BaseCompilerProperties); ok {
110 archDisabledSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_disabled_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800111 moduleAttrs.Tidy_disabled_srcs.SetSelectValue(axis, cfg, archDisabledSrcs)
Sam Delmerico4c902d62022-11-02 14:17:15 -0400112 archTimeoutSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_timeout_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800113 moduleAttrs.Tidy_timeout_srcs.SetSelectValue(axis, cfg, archTimeoutSrcs)
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400114 }
115 }
Sam Delmericofb3bb322022-10-21 10:42:24 -0400116 }
Jingwen Chen53681ef2021-04-29 08:15:13 +0000117}
118
Sam Delmericoc7681022022-02-04 21:01:20 +0000119// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000120func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400121 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
122 // macro.
123 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -0400124 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
125
126 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -0400127 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -0400128 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
129 return labelStr, false
130 }
Yu Liu2aa806b2022-09-01 11:54:47 -0700131 // If the filegroup is already converted to aidl_library or proto_library,
132 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
133 fg, _ := m.(android.FileGroupAsLibrary)
134 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -0400135 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000136 }
Liz Kammer12615db2021-09-28 09:19:17 -0400137 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400138 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000139 }
140
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400141 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +0000142 labels := bazel.LabelPartitions{
143 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500144 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
145 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -0700146 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -0400147 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000148 // TODO(http://b/231968910): If there is ever a filegroup target that
149 // contains .l or .ll files we will need to find a way to add a
150 // LabelMapper for these that identifies these filegroups and
151 // converts them appropriately
152 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
153 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400154 // C++ is the "catch-all" group, and comprises generated sources because we don't
155 // know the language of these sources until the genrule is executed.
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000156 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
157 syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
Spandan Dasdf4c2132023-05-09 23:58:52 +0000158 yaccSrcPartition: bazel.LabelPartition{Extensions: []string{".y", "yy"}},
Sam Delmericoc7681022022-02-04 21:01:20 +0000159 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000160
Sam Delmericoc7681022022-02-04 21:01:20 +0000161 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000162}
163
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000164// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000165func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000166 lib, ok := module.compiler.(*libraryDecorator)
167 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400168 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000169 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000170 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
171}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000172
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000173// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000174func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000175 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000176}
177
178// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000179func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000180 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400181}
182
Liz Kammer7a210ac2021-09-22 15:52:58 -0400183type depsPartition struct {
184 export bazel.LabelList
185 implementation bazel.LabelList
186}
187
Jingwen Chen55bc8202021-11-02 06:40:51 +0000188type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400189
Jingwen Chen55bc8202021-11-02 06:40:51 +0000190func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400191 if !exportsDeps {
192 return depsPartition{
193 implementation: fn(ctx, allDeps),
194 }
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),
201 implementation: fn(ctx, implementation),
202 }
203}
204
Jingwen Chen55bc8202021-11-02 06:40:51 +0000205type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400206
Jingwen Chen55bc8202021-11-02 06:40:51 +0000207func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400208 if !exportsDeps {
209 return depsPartition{
210 implementation: fn(ctx, allDeps, excludes),
211 }
212 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400213 implementation, export := android.FilterList(allDeps, exportedDeps)
214
215 return depsPartition{
216 export: fn(ctx, export, excludes),
217 implementation: fn(ctx, implementation, excludes),
218 }
219}
220
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000221func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
222 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800223 for cfg, props := range configToProps {
224 parseFunc(axis, cfg, props)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000225 }
226 }
227}
228
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000229// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Liz Kammeraceec252023-03-24 09:46:36 -0400230func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400231 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000232
Liz Kammer9abd62d2021-05-21 08:37:59 -0400233 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000234 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutHiddenVisibility))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000235 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400236 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400237
Liz Kammer2b8004b2021-10-04 13:55:44 -0400238 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400239 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
240 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
241
Liz Kammer2b8004b2021-10-04 13:55:44 -0400242 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400243 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
244 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
245
246 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500247 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000248 }
Liz Kammer135bf552021-08-11 10:46:06 -0400249 // system_dynamic_deps distinguishes between nil/empty list behavior:
250 // nil -> use default values
251 // empty list -> no values specified
252 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000253
Liz Kammeraceec252023-03-24 09:46:36 -0400254 var apexAvailable []string
Jingwen Chenbcf53042021-05-26 04:42:42 +0000255 if isStatic {
Liz Kammeraceec252023-03-24 09:46:36 -0400256 apexAvailable = lib.StaticProperties.Static.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000257 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
258 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
259 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000260 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000261 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000262 } else {
Liz Kammeraceec252023-03-24 09:46:36 -0400263 apexAvailable = lib.SharedProperties.Shared.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000264 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
265 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
266 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000267 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000268 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000269 }
270
Liz Kammerae3994e2021-10-19 09:45:48 -0400271 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
272 attrs.Srcs = partitionedSrcs[cppSrcPartition]
273 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
274 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000275
Spandan Das39b6cc52023-04-12 19:05:49 +0000276 attrs.Apex_available = android.ConvertApexAvailableToTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), apexAvailable)
Liz Kammeraceec252023-03-24 09:46:36 -0400277
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000278 attrs.Features.Append(convertHiddenVisibilityToFeatureStaticOrShared(ctx, module, isStatic))
279
Liz Kammer12615db2021-09-28 09:19:17 -0400280 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
281 // TODO(b/208815215): determine whether this is used and add support if necessary
282 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
283 }
284
Jingwen Chenbcf53042021-05-26 04:42:42 +0000285 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000286}
287
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400288// Convenience struct to hold all attributes parsed from prebuilt properties.
289type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000290 Src bazel.LabelAttribute
291 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400292}
293
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000294func parseSrc(ctx android.BazelConversionPathContext, srcLabelAttribute *bazel.LabelAttribute, axis bazel.ConfigurationAxis, config string, srcs []string) {
295 srcFileError := func() {
296 ctx.ModuleErrorf("parseSrc: Expected at most one source file for %s %s\n", axis, config)
297 }
298 if len(srcs) > 1 {
299 srcFileError()
300 return
301 } else if len(srcs) == 0 {
302 return
303 }
304 if srcLabelAttribute.SelectValue(axis, config) != nil {
305 srcFileError()
306 return
307 }
308 srcLabelAttribute.SetSelectValue(axis, config, android.BazelLabelForModuleSrcSingle(ctx, srcs[0]))
309}
310
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000311// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000312func 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 +0000313
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400314 var srcLabelAttribute bazel.LabelAttribute
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000315 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
316 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000317 parseSrc(ctx, &srcLabelAttribute, axis, config, prebuiltLinkerProperties.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000318 }
319 })
320
321 var enabledLabelAttribute bazel.BoolAttribute
322 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
323 if props.Enabled != nil {
324 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
325 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000326 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000327 }
328
329 if isStatic {
330 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
331 if staticProperties, ok := props.(*StaticProperties); ok {
332 parseAttrs(axis, config, staticProperties.Static)
333 }
334 })
335 } else {
336 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
337 if sharedProperties, ok := props.(*SharedProperties); ok {
338 parseAttrs(axis, config, sharedProperties.Shared)
339 }
340 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400341 }
342
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400343 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000344 Src: srcLabelAttribute,
345 Enabled: enabledLabelAttribute,
346 }
347}
348
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000349func bp2BuildParsePrebuiltBinaryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
350 var srcLabelAttribute bazel.LabelAttribute
351 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
352 if props, ok := props.(*prebuiltLinkerProperties); ok {
353 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000354 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000355 })
356
357 return prebuiltAttributes{
358 Src: srcLabelAttribute,
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400359 }
360}
361
Colin Crossc5075e92022-12-05 16:46:39 -0800362func bp2BuildParsePrebuiltObjectProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
363 var srcLabelAttribute bazel.LabelAttribute
364 bp2BuildPropParseHelper(ctx, module, &prebuiltObjectProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
365 if props, ok := props.(*prebuiltObjectProperties); ok {
366 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
367 }
368 })
369
370 return prebuiltAttributes{
371 Src: srcLabelAttribute,
372 }
373}
374
Liz Kammere6583482021-10-19 13:56:10 -0400375type baseAttributes struct {
376 compilerAttributes
377 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400378
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000379 // A combination of compilerAttributes.features and linkerAttributes.features, as well as sanitizer features
Cole Faust5fa4e962022-08-22 14:31:04 -0700380 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400381 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400382 aidlDependency *bazel.LabelAttribute
Yu Liuf01a0f02022-12-07 15:45:30 -0800383 Native_coverage *bool
Liz Kammere6583482021-10-19 13:56:10 -0400384}
385
Jingwen Chen107c0de2021-04-09 10:43:12 +0000386// Convenience struct to hold all attributes parsed from compiler properties.
387type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400388 // Options for all languages
389 copts bazel.StringListAttribute
390 // Assembly options and sources
391 asFlags bazel.StringListAttribute
392 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700393 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400394 // C options and sources
395 conlyFlags bazel.StringListAttribute
396 cSrcs bazel.LabelListAttribute
397 // C++ options and sources
398 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000399 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400400
Liz Kammer084d6a92023-06-22 16:23:53 -0400401 // xsd config sources
402 xsdInSrcs bazel.StringListAttribute
403
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000404 // Lex sources and options
405 lSrcs bazel.LabelListAttribute
406 llSrcs bazel.LabelListAttribute
407 lexopts bazel.StringListAttribute
408
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000409 // Sysprop sources
410 syspropSrcs bazel.LabelListAttribute
411
Spandan Dasdf4c2132023-05-09 23:58:52 +0000412 // Yacc sources
413 yaccSrc *bazel.LabelAttribute
414 yaccFlags bazel.StringListAttribute
415 yaccGenLocationHeader bazel.BoolAttribute
416 yaccGenPositionHeader bazel.BoolAttribute
417
Liz Kammere6583482021-10-19 13:56:10 -0400418 hdrs bazel.LabelListAttribute
419
Chris Parsons2c788392021-08-10 11:58:07 -0400420 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000421
422 // Not affected by arch variants
423 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500424 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000425 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400426
427 localIncludes bazel.StringListAttribute
428 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400429
Liz Kammer1263d9b2021-12-10 14:28:20 -0500430 includes BazelIncludes
431
Liz Kammer12615db2021-09-28 09:19:17 -0400432 protoSrcs bazel.LabelListAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400433 aidlSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000434
435 stubsSymbolFile *string
436 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700437
438 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500439
Spandan Das39ccf932023-05-26 18:03:39 +0000440 stem bazel.StringAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500441 suffix bazel.StringAttribute
Vinh Tran99270ea2022-11-28 11:15:23 -0500442
443 fdoProfile bazel.LabelAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000444}
445
Liz Kammercac7f692021-12-16 14:19:32 -0500446type filterOutFn func(string) bool
447
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000448// filterOutHiddenVisibility removes the flag specifying hidden visibility as
449// this flag is converted to a toolchain feature
450func filterOutHiddenVisibility(flag string) bool {
451 return flag == config.VisibilityHiddenFlag
452}
453
Liz Kammercac7f692021-12-16 14:19:32 -0500454func filterOutStdFlag(flag string) bool {
455 return strings.HasPrefix(flag, "-std=")
456}
457
Alix1be00d42022-05-16 22:56:04 +0000458func filterOutClangUnknownCflags(flag string) bool {
459 for _, f := range config.ClangUnknownCflags {
460 if f == flag {
461 return true
462 }
463 }
464 return false
465}
466
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000467func parseCommandLineFlags(soongFlags []string, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400468 var result []string
469 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000470 skipFlag := false
471 for _, filter := range filterOut {
472 if filter != nil && filter(flag) {
473 skipFlag = true
474 }
475 }
476 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500477 continue
478 }
Liz Kammere6583482021-10-19 13:56:10 -0400479 // Soong's cflags can contain spaces, like `-include header.h`. For
480 // Bazel's copts, split them up to be compatible with the
481 // no_copts_tokenization feature.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000482 result = append(result, strings.Split(flag, " ")...)
Liz Kammere6583482021-10-19 13:56:10 -0400483 }
484 return result
485}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000486
Jingwen Chen55bc8202021-11-02 06:40:51 +0000487func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400488 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
489 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
Liz Kammer084d6a92023-06-22 16:23:53 -0400490 srcsList, xsdList, ok := parseSrcs(ctx, props)
491
492 if ok {
Liz Kammere6583482021-10-19 13:56:10 -0400493 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400494 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400495 if len(xsdList) > 0 {
496 ca.xsdInSrcs.SetSelectValue(axis, config, xsdList)
497 }
Chris Parsons990c4f42021-05-25 12:10:58 -0400498
Liz Kammere6583482021-10-19 13:56:10 -0400499 localIncludeDirs := props.Local_include_dirs
500 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500501 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400502 if includeBuildDirectory(props.Include_build_directory) {
503 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400504 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000505 }
506
Liz Kammere6583482021-10-19 13:56:10 -0400507 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
508 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
509
Cole Faust5fa4e962022-08-22 14:31:04 -0700510 instructionSet := proptools.StringDefault(props.Instruction_set, "")
511 if instructionSet == "arm" {
Trevor Radcliffe5f0c2ac2023-05-15 18:00:59 +0000512 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm"})
Cole Faust5fa4e962022-08-22 14:31:04 -0700513 } else if instructionSet != "" && instructionSet != "thumb" {
514 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
515 }
516
Liz Kammercac7f692021-12-16 14:19:32 -0500517 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
518 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
519 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
520 // cases.
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000521 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutClangUnknownCflags, filterOutHiddenVisibility))
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000522 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
523 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, filterOutClangUnknownCflags))
524 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400525 ca.rtti.SetSelectValue(axis, config, props.Rtti)
526}
527
Jingwen Chen55bc8202021-11-02 06:40:51 +0000528func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000529 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
530 if stlProps, ok := props.(*StlProperties); ok {
531 if stlProps.Stl == nil {
532 return
533 }
534 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400535 stl := deduplicateStlInput(*stlProps.Stl)
536 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000537 } else if ca.stl != stlProps.Stl {
538 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 -0400539 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000540 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000541 })
Liz Kammere6583482021-10-19 13:56:10 -0400542}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000543
Jingwen Chen55bc8202021-11-02 06:40:51 +0000544func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400545 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400546 "Cflags": &ca.copts,
547 "Asflags": &ca.asFlags,
Yu Liu93893ba2023-05-01 13:49:52 -0700548 "Cppflags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400549 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400550 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000551 if productConfigProps, exists := productVariableProps[propName]; exists {
552 for productConfigProp, prop := range productConfigProps {
553 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400554 if !ok {
555 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
556 }
Cole Faust150f9a52023-04-26 10:52:24 -0700557 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name())
Jingwen Chen25825ca2021-11-15 12:28:43 +0000558 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400559 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400560 }
561 }
Liz Kammere6583482021-10-19 13:56:10 -0400562}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400563
Jingwen Chen55bc8202021-11-02 06:40:51 +0000564func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400565 ca.srcs.ResolveExcludes()
566 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
567
Liz Kammer12615db2021-09-28 09:19:17 -0400568 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400569 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400570
Liz Kammere6583482021-10-19 13:56:10 -0400571 for p, lla := range partitionedSrcs {
572 // if there are no sources, there is no need for headers
573 if lla.IsEmpty() {
574 continue
575 }
576 lla.Append(implementationHdrs)
577 partitionedSrcs[p] = lla
578 }
579
580 ca.srcs = partitionedSrcs[cppSrcPartition]
581 ca.cSrcs = partitionedSrcs[cSrcPartition]
582 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700583 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000584 ca.lSrcs = partitionedSrcs[lSrcPartition]
585 ca.llSrcs = partitionedSrcs[llSrcPartition]
Spandan Dasdf4c2132023-05-09 23:58:52 +0000586 if yacc := partitionedSrcs[yaccSrcPartition]; !yacc.IsEmpty() {
587 if len(yacc.Value.Includes) > 1 {
588 ctx.PropertyErrorf("srcs", "Found multiple yacc (.y/.yy) files in library")
589 }
590 ca.yaccSrc = bazel.MakeLabelAttribute(yacc.Value.Includes[0].Label)
591 }
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000592 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400593
594 ca.absoluteIncludes.DeduplicateAxesFromBase()
595 ca.localIncludes.DeduplicateAxesFromBase()
596}
597
598// Parse srcs from an arch or OS's props value.
Liz Kammer084d6a92023-06-22 16:23:53 -0400599func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, []string, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400600 anySrcs := false
601 // Add srcs-like dependencies such as generated files.
602 // First create a LabelList containing these dependencies, then merge the values with srcs.
Liz Kammer084d6a92023-06-22 16:23:53 -0400603 genSrcs, xsd := android.PartitionXsdSrcs(ctx, props.Generated_sources)
Spandan Das922171d2023-05-31 23:32:40 +0000604 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, genSrcs, props.Exclude_generated_sources)
Liz Kammere6583482021-10-19 13:56:10 -0400605 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
606 anySrcs = true
607 }
608
609 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400610
Liz Kammere6583482021-10-19 13:56:10 -0400611 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
612 anySrcs = true
613 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400614
Liz Kammer084d6a92023-06-22 16:23:53 -0400615 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), xsd, anySrcs
Liz Kammere6583482021-10-19 13:56:10 -0400616}
617
Liz Kammera5a29de2022-05-25 23:19:37 -0400618func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
619 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500620 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
621 // Defaults are handled by the toolchain definition.
622 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400623 stdVal := proptools.StringDefault(std, defaultVal)
624 if stdVal == "experimental" || stdVal == defaultVal {
625 if stdVal == "experimental" {
626 stdVal = prefix + "_std_experimental"
627 }
628 if !useGnu {
629 stdVal += "_no_gnu"
630 }
631 } else if !useGnu {
632 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500633 }
634
Liz Kammera5a29de2022-05-25 23:19:37 -0400635 if stdVal == defaultVal {
636 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500637 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400638 return &stdVal
639}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500640
Liz Kammera5a29de2022-05-25 23:19:37 -0400641func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
642 useGnu := useGnuExtensions(gnu_extensions)
643
644 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400645}
646
Liz Kammer1263d9b2021-12-10 14:28:20 -0500647// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
648// is fully-qualified.
649// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
650func packageFromLabel(label string) (string, bool) {
651 split := strings.Split(label, ":")
652 if len(split) != 2 {
653 return "", false
654 }
655 if split[0] == "" {
656 return ".", false
657 }
658 // remove leading "//"
659 return split[0][2:], true
660}
661
662// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
663func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
664 for _, hdr := range labelList.Includes {
665 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
666 absolute = append(absolute, pkg)
667 } else if pkg != "" {
668 relative = append(relative, pkg)
669 }
670 }
671 return relative, absolute
672}
673
Cole Faust7071a052022-07-29 15:58:33 -0700674type YasmAttributes struct {
675 Srcs bazel.LabelListAttribute
676 Flags bazel.StringListAttribute
677 Include_dirs bazel.StringListAttribute
678}
679
680func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
681 if ca.asmSrcs.IsEmpty() {
682 return nil
683 }
684
685 // Yasm needs the include directories from both local_includes and
686 // export_include_dirs. We don't care about actually exporting them from the
687 // yasm rule though, because they will also be present on the cc_ rule that
688 // wraps this yasm rule.
689 includes := ca.localIncludes.Clone()
690 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
691 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
692 if len(flagExporterProperties.Export_include_dirs) > 0 {
693 x := bazel.StringListAttribute{}
694 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
695 includes.Append(x)
696 }
697 }
698 })
699
700 ctx.CreateBazelTargetModule(
701 bazel.BazelTargetModuleProperties{
702 Rule_class: "yasm",
703 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
704 },
705 android.CommonAttributes{Name: m.Name() + "_yasm"},
706 &YasmAttributes{
707 Srcs: ca.asmSrcs,
708 Flags: ca.asFlags,
709 Include_dirs: *includes,
710 })
711
712 // We only want to add a dependency on the _yasm target if there are asm
713 // sources in the current configuration. If there are unconfigured asm
714 // sources, always add the dependency. Otherwise, add the dependency only
715 // on the configuration axes and values that had asm sources.
716 if len(ca.asmSrcs.Value.Includes) > 0 {
717 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
718 }
719
720 ret := &bazel.LabelAttribute{}
721 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800722 for cfg := range ca.asmSrcs.ConfigurableValues[axis] {
723 ret.SetSelectValue(axis, cfg, bazel.Label{Label: ":" + m.Name() + "_yasm"})
Cole Faust7071a052022-07-29 15:58:33 -0700724 }
725 }
726 return ret
727}
728
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000729// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400730func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400731 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
732 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000733 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400734
735 var implementationHdrs bazel.LabelListAttribute
736
737 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
738 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
739 for axis, configMap := range cp {
740 if _, ok := axisToConfigs[axis]; !ok {
741 axisToConfigs[axis] = map[string]bool{}
742 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800743 for cfg := range configMap {
744 axisToConfigs[axis][cfg] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400745 }
746 }
747 }
Liz Kammere6583482021-10-19 13:56:10 -0400748 allAxesAndConfigs(archVariantCompilerProps)
749 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000750 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400751
Liz Kammere6583482021-10-19 13:56:10 -0400752 compilerAttrs := compilerAttributes{}
753 linkerAttrs := linkerAttributes{}
754
Vinh Tran367d89d2023-04-28 11:21:25 -0400755 var aidlLibs bazel.LabelList
756
Chris Parsons7b3289b2023-01-26 17:30:44 -0500757 // Iterate through these axes in a deterministic order. This is required
758 // because processing certain dependencies may result in concatenating
759 // elements along other axes. (For example, processing NoConfig may result
760 // in elements being added to InApex). This is thus the only way to ensure
761 // that the order of entries in each list is in a predictable order.
762 for _, axis := range bazel.SortedConfigurationAxes(axisToConfigs) {
763 configs := axisToConfigs[axis]
Sasha Smundak39a301c2022-12-29 17:11:49 -0800764 for cfg := range configs {
Liz Kammer084d6a92023-06-22 16:23:53 -0400765 var allHdrs, allHdrsXsd []string
Sasha Smundak39a301c2022-12-29 17:11:49 -0800766 if baseCompilerProps, ok := archVariantCompilerProps[axis][cfg].(*BaseCompilerProperties); ok {
Liz Kammer084d6a92023-06-22 16:23:53 -0400767 allHdrs, allHdrsXsd = android.PartitionXsdSrcs(ctx, baseCompilerProps.Generated_headers)
Spandan Das922171d2023-05-31 23:32:40 +0000768
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000769 if baseCompilerProps.Lex != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800770 compilerAttrs.lexopts.SetSelectValue(axis, cfg, baseCompilerProps.Lex.Flags)
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000771 }
Spandan Dasdf4c2132023-05-09 23:58:52 +0000772 if baseCompilerProps.Yacc != nil {
773 compilerAttrs.yaccFlags.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Flags)
774 compilerAttrs.yaccGenLocationHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_location_hh)
775 compilerAttrs.yaccGenPositionHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_position_hh)
776 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800777 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, cfg, baseCompilerProps)
Vinh Tran367d89d2023-04-28 11:21:25 -0400778 aidlLibs.Append(android.BazelLabelForModuleDeps(ctx, baseCompilerProps.Aidl.Libs))
Liz Kammere6583482021-10-19 13:56:10 -0400779 }
780
Liz Kammer084d6a92023-06-22 16:23:53 -0400781 var exportHdrs, exportHdrsXsd []string
Liz Kammere6583482021-10-19 13:56:10 -0400782
Sasha Smundak39a301c2022-12-29 17:11:49 -0800783 if baseLinkerProps, ok := archVariantLinkerProps[axis][cfg].(*BaseLinkerProperties); ok {
Liz Kammer084d6a92023-06-22 16:23:53 -0400784 exportHdrs, exportHdrsXsd = android.PartitionXsdSrcs(ctx, baseLinkerProps.Export_generated_headers)
Liz Kammer48cdbeb2023-03-17 10:17:50 -0400785 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module, axis, cfg, baseLinkerProps)
Liz Kammere6583482021-10-19 13:56:10 -0400786 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400787
788 // in the synthetic bp2build workspace, xsd sources are compiled to a static library
789 xsdList := compilerAttrs.xsdInSrcs.SelectValue(axis, cfg)
790 allHdrsXsd = android.FirstUniqueStrings(append(xsdList, allHdrsXsd...))
Liz Kammere6583482021-10-19 13:56:10 -0400791 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
Liz Kammer084d6a92023-06-22 16:23:53 -0400792 xsdConfigLibs := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrsXsd, exportHdrsXsd, bazelLabelForXsdConfig)
793
Sasha Smundak39a301c2022-12-29 17:11:49 -0800794 implementationHdrs.SetSelectValue(axis, cfg, headers.implementation)
795 compilerAttrs.hdrs.SetSelectValue(axis, cfg, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500796
797 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800798 compilerAttrs.includes.Includes.SetSelectValue(axis, cfg, exportIncludes)
799 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, cfg, exportAbsoluteIncludes)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500800
801 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800802 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, cfg)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500803 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400804
Sasha Smundak39a301c2022-12-29 17:11:49 -0800805 compilerAttrs.absoluteIncludes.SetSelectValue(axis, cfg, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400806
Sasha Smundak39a301c2022-12-29 17:11:49 -0800807 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, cfg)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500808 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400809
Sasha Smundak39a301c2022-12-29 17:11:49 -0800810 compilerAttrs.localIncludes.SetSelectValue(axis, cfg, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000811
Sasha Smundak39a301c2022-12-29 17:11:49 -0800812 if libraryProps, ok := archVariantLibraryProperties[axis][cfg].(*LibraryProperties); ok {
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000813 if axis == bazel.NoConfigAxis {
Sam Delmerico75dbca22023-04-20 13:13:25 +0000814 if libraryProps.Stubs.Symbol_file != nil {
815 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
816 versions := android.CopyOf(libraryProps.Stubs.Versions)
817 normalizeVersions(ctx, versions)
818 versions = addCurrentVersionIfNotPresent(versions)
819 compilerAttrs.stubsVersions.SetSelectValue(axis, cfg, versions)
820 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000821 }
Spandan Das39ccf932023-05-26 18:03:39 +0000822 if stem := libraryProps.Stem; stem != nil {
823 compilerAttrs.stem.SetSelectValue(axis, cfg, stem)
824 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500825 if suffix := libraryProps.Suffix; suffix != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800826 compilerAttrs.suffix.SetSelectValue(axis, cfg, suffix)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500827 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000828 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400829
830 if len(allHdrsXsd) > 0 {
831 wholeStaticLibs := linkerAttrs.implementationWholeArchiveDeps.SelectValue(axis, cfg)
832 (&wholeStaticLibs).Append(xsdConfigLibs.implementation)
833 linkerAttrs.implementationWholeArchiveDeps.SetSelectValue(axis, cfg, wholeStaticLibs)
834 wholeStaticLibs = linkerAttrs.wholeArchiveDeps.SelectValue(axis, cfg)
835 (&wholeStaticLibs).Append(xsdConfigLibs.export)
836 linkerAttrs.wholeArchiveDeps.SetSelectValue(axis, cfg, wholeStaticLibs)
837 }
Liz Kammere6583482021-10-19 13:56:10 -0400838 }
839 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400840
Liz Kammere6583482021-10-19 13:56:10 -0400841 compilerAttrs.convertStlProps(ctx, module)
842 (&linkerAttrs).convertStripProps(ctx, module)
843
Yu Liuf01a0f02022-12-07 15:45:30 -0800844 var nativeCoverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -0700845 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
846 !Bool(module.coverage.Properties.Native_coverage) {
Yu Liuf01a0f02022-12-07 15:45:30 -0800847 nativeCoverage = BoolPtr(false)
Yu Liu8d82ac52022-05-17 15:13:28 -0700848 }
849
Cole Faust912bc882023-03-08 12:29:50 -0800850 productVariableProps := android.ProductVariableProperties(ctx, ctx.Module())
Liz Kammere6583482021-10-19 13:56:10 -0400851
852 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
853 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
854
855 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500856 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400857
Cole Faust7071a052022-07-29 15:58:33 -0700858 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
859
Liz Kammer12615db2021-09-28 09:19:17 -0400860 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
861
862 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
863 // which. This will add the newly generated proto library to the appropriate attribute and nothing
864 // to the other
865 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
866 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400867
Vinh Tran367d89d2023-04-28 11:21:25 -0400868 aidlDep := bp2buildCcAidlLibrary(
869 ctx, module,
870 compilerAttrs.aidlSrcs,
871 bazel.LabelListAttribute{
872 Value: aidlLibs,
873 },
874 linkerAttrs,
Vinh Trane6842942023-04-28 11:21:25 -0400875 compilerAttrs,
Vinh Tran367d89d2023-04-28 11:21:25 -0400876 )
Vinh Tranfde57eb2022-08-29 17:46:58 -0400877 if aidlDep != nil {
878 if lib, ok := module.linker.(*libraryDecorator); ok {
879 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
880 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
881 } else {
882 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
883 }
884 }
885 }
Liz Kammer12615db2021-09-28 09:19:17 -0400886
Spandan Dasdf4c2132023-05-09 23:58:52 +0000887 // Create a cc_yacc_static_library if srcs contains .y/.yy files
888 // This internal target will produce an .a file that will be statically linked to the parent library
889 if yaccDep := bp2buildCcYaccLibrary(ctx, compilerAttrs, linkerAttrs); yaccDep != nil {
890 (&linkerAttrs).implementationWholeArchiveDeps.Add(yaccDep)
891 }
892
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000893 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
894 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
895 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
896
Vinh Tran99270ea2022-11-28 11:15:23 -0500897 if module.afdo != nil && module.afdo.Properties.Afdo {
898 fdoProfileDep := bp2buildFdoProfile(ctx, module)
899 if fdoProfileDep != nil {
900 (&compilerAttrs).fdoProfile.SetValue(*fdoProfileDep)
901 }
902 }
903
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000904 if !compilerAttrs.syspropSrcs.IsEmpty() {
905 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
906 }
907
Zi Wang9f609db2023-01-04 11:06:54 -0800908 linkerAttrs.wholeArchiveDeps.Prepend = true
909 linkerAttrs.deps.Prepend = true
910 compilerAttrs.localIncludes.Prepend = true
911 compilerAttrs.absoluteIncludes.Prepend = true
912 compilerAttrs.hdrs.Prepend = true
913
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000914 features := compilerAttrs.features.Clone().Append(linkerAttrs.features).Append(bp2buildSanitizerFeatures(ctx, module))
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +0000915 features = features.Append(bp2buildLtoFeatures(ctx, module))
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000916 features = features.Append(convertHiddenVisibilityToFeatureBase(ctx, module))
Cole Faust5fa4e962022-08-22 14:31:04 -0700917 features.DeduplicateAxesFromBase()
918
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +0000919 addMuslSystemDynamicDeps(ctx, linkerAttrs)
920
Liz Kammere6583482021-10-19 13:56:10 -0400921 return baseAttributes{
922 compilerAttrs,
923 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700924 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400925 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400926 aidlDep,
Yu Liuf01a0f02022-12-07 15:45:30 -0800927 nativeCoverage,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000928 }
929}
930
Spandan Dasdf4c2132023-05-09 23:58:52 +0000931type ccYaccLibraryAttributes struct {
932 Src bazel.LabelAttribute
933 Flags bazel.StringListAttribute
934 Gen_location_hh bazel.BoolAttribute
935 Gen_position_hh bazel.BoolAttribute
936 Local_includes bazel.StringListAttribute
937 Implementation_deps bazel.LabelListAttribute
938 Implementation_dynamic_deps bazel.LabelListAttribute
939}
940
941func bp2buildCcYaccLibrary(ctx android.Bp2buildMutatorContext, ca compilerAttributes, la linkerAttributes) *bazel.LabelAttribute {
942 if ca.yaccSrc == nil {
943 return nil
944 }
945 yaccLibraryLabel := ctx.Module().Name() + "_yacc"
946 ctx.CreateBazelTargetModule(
947 bazel.BazelTargetModuleProperties{
948 Rule_class: "cc_yacc_static_library",
949 Bzl_load_location: "//build/bazel/rules/cc:cc_yacc_library.bzl",
950 },
951 android.CommonAttributes{
952 Name: yaccLibraryLabel,
953 },
954 &ccYaccLibraryAttributes{
955 Src: *ca.yaccSrc,
956 Flags: ca.yaccFlags,
957 Gen_location_hh: ca.yaccGenLocationHeader,
958 Gen_position_hh: ca.yaccGenPositionHeader,
959 Local_includes: ca.localIncludes,
960 Implementation_deps: la.implementationDeps,
961 Implementation_dynamic_deps: la.implementationDynamicDeps,
962 },
963 )
964
965 yaccLibrary := &bazel.LabelAttribute{
966 Value: &bazel.Label{
967 Label: ":" + yaccLibraryLabel,
968 },
969 }
970 return yaccLibrary
971}
972
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +0000973// As a workaround for b/261657184, we are manually adding the default value
974// of system_dynamic_deps for the linux_musl os.
975// TODO: Solve this properly
976func addMuslSystemDynamicDeps(ctx android.Bp2buildMutatorContext, attrs linkerAttributes) {
977 systemDynamicDeps := attrs.systemDynamicDeps.SelectValue(bazel.OsConfigurationAxis, "linux_musl")
978 if attrs.systemDynamicDeps.HasAxisSpecificValues(bazel.OsConfigurationAxis) && systemDynamicDeps.IsNil() {
979 attrs.systemDynamicDeps.SetSelectValue(bazel.OsConfigurationAxis, "linux_musl", android.BazelLabelForModuleDeps(ctx, config.MuslDefaultSharedLibraries))
980 }
981}
982
Vinh Tran99270ea2022-11-28 11:15:23 -0500983type fdoProfileAttributes struct {
984 Absolute_path_profile string
985}
986
987func bp2buildFdoProfile(
988 ctx android.Bp2buildMutatorContext,
989 m *Module,
990) *bazel.Label {
991 for _, project := range globalAfdoProfileProjects {
Vinh Tranbc9c8b42022-12-09 12:03:52 -0500992 // Ensure handcrafted BUILD file exists in the project
993 BUILDPath := android.ExistentPathForSource(ctx, project, "BUILD")
994 if BUILDPath.Valid() {
995 // We handcraft a BUILD file with fdo_profile targets that use the existing profiles in the project
996 // This implementation is assuming that every afdo profile in globalAfdoProfileProjects already has
997 // an associated fdo_profile target declared in the same package.
998 // TODO(b/260714900): Handle arch-specific afdo profiles (e.g. `<module-name>-arm<64>.afdo`)
999 path := android.ExistentPathForSource(ctx, project, m.Name()+".afdo")
1000 if path.Valid() {
1001 // FIXME: Some profiles only exist internally and are not released to AOSP.
1002 // When generated BUILD files are checked in, we'll run into merge conflict.
1003 // The cc_library_shared target in AOSP won't have reference to an fdo_profile target because
1004 // the profile doesn't exist. Internally, the same cc_library_shared target will
1005 // have reference to the fdo_profile.
1006 // For more context, see b/258682955#comment2
1007 fdoProfileLabel := "//" + strings.TrimSuffix(project, "/") + ":" + m.Name()
1008 return &bazel.Label{
1009 Label: fdoProfileLabel,
1010 }
Vinh Tran99270ea2022-11-28 11:15:23 -05001011 }
1012 }
1013 }
1014
1015 return nil
1016}
1017
Vinh Tran9f6796a2022-08-16 13:10:31 -04001018func bp2buildCcAidlLibrary(
1019 ctx android.Bp2buildMutatorContext,
1020 m *Module,
Vinh Tran367d89d2023-04-28 11:21:25 -04001021 aidlSrcs bazel.LabelListAttribute,
1022 aidlLibs bazel.LabelListAttribute,
Vinh Tran395a1e92022-09-16 18:27:29 -04001023 linkerAttrs linkerAttributes,
Vinh Trane6842942023-04-28 11:21:25 -04001024 compilerAttrs compilerAttributes,
Vinh Tran9f6796a2022-08-16 13:10:31 -04001025) *bazel.LabelAttribute {
Vinh Tran367d89d2023-04-28 11:21:25 -04001026 var aidlLibsFromSrcs, aidlFiles bazel.LabelListAttribute
1027 apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), ctx.Module())
1028
1029 if !aidlSrcs.IsEmpty() {
1030 aidlLibsFromSrcs, aidlFiles = aidlSrcs.Partition(func(src bazel.Label) bool {
Vinh Trana3b8b782022-09-14 11:40:24 -04001031 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
1032 fg.ShouldConvertToAidlLibrary(ctx) {
1033 return true
1034 }
1035 return false
1036 })
Vinh Tran9f6796a2022-08-16 13:10:31 -04001037
Vinh Tran367d89d2023-04-28 11:21:25 -04001038 if !aidlFiles.IsEmpty() {
Vinh Trana3b8b782022-09-14 11:40:24 -04001039 aidlLibName := m.Name() + "_aidl_library"
1040 ctx.CreateBazelTargetModule(
1041 bazel.BazelTargetModuleProperties{
1042 Rule_class: "aidl_library",
Sam Delmericoe55bf082023-03-31 09:47:28 -04001043 Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
Vinh Trana3b8b782022-09-14 11:40:24 -04001044 },
Vinh Tran367d89d2023-04-28 11:21:25 -04001045 android.CommonAttributes{
1046 Name: aidlLibName,
Liz Kammer2b3f56e2023-03-23 11:51:49 -04001047 Tags: apexAvailableTags,
Vinh Trana3b8b782022-09-14 11:40:24 -04001048 },
Vinh Tran367d89d2023-04-28 11:21:25 -04001049 &aidlLibraryAttributes{
1050 Srcs: aidlFiles,
Vinh Trana3b8b782022-09-14 11:40:24 -04001051 },
1052 )
Vinh Tran367d89d2023-04-28 11:21:25 -04001053 aidlLibsFromSrcs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
Vinh Trana3b8b782022-09-14 11:40:24 -04001054 }
Vinh Tran9f6796a2022-08-16 13:10:31 -04001055 }
1056
Vinh Tran367d89d2023-04-28 11:21:25 -04001057 allAidlLibs := aidlLibs.Clone()
1058 allAidlLibs.Append(aidlLibsFromSrcs)
1059
1060 if !allAidlLibs.IsEmpty() {
1061 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
1062 // Since parent cc_library already has these dependencies, we can add them as implementation
1063 // deps so that they don't re-export
1064 implementationDeps := linkerAttrs.deps.Clone()
1065 implementationDeps.Append(linkerAttrs.implementationDeps)
1066 implementationDynamicDeps := linkerAttrs.dynamicDeps.Clone()
1067 implementationDynamicDeps.Append(linkerAttrs.implementationDynamicDeps)
1068
1069 sdkAttrs := bp2BuildParseSdkAttributes(m)
1070
Vinh Trane6842942023-04-28 11:21:25 -04001071 exportedIncludes := bp2BuildParseExportedIncludes(ctx, m, &compilerAttrs.includes)
1072 includeAttrs := includesAttributes{
1073 Export_includes: exportedIncludes.Includes,
1074 Export_absolute_includes: exportedIncludes.AbsoluteIncludes,
1075 Export_system_includes: exportedIncludes.SystemIncludes,
1076 Local_includes: compilerAttrs.localIncludes,
1077 Absolute_includes: compilerAttrs.absoluteIncludes,
1078 }
1079
Vinh Tran367d89d2023-04-28 11:21:25 -04001080 ctx.CreateBazelTargetModule(
1081 bazel.BazelTargetModuleProperties{
1082 Rule_class: "cc_aidl_library",
1083 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
1084 },
1085 android.CommonAttributes{Name: ccAidlLibrarylabel},
1086 &ccAidlLibraryAttributes{
1087 Deps: *allAidlLibs,
1088 Implementation_deps: *implementationDeps,
1089 Implementation_dynamic_deps: *implementationDynamicDeps,
1090 Tags: apexAvailableTags,
1091 sdkAttributes: sdkAttrs,
Vinh Trane6842942023-04-28 11:21:25 -04001092 includesAttributes: includeAttrs,
Vinh Tran367d89d2023-04-28 11:21:25 -04001093 },
1094 )
1095 label := &bazel.LabelAttribute{
1096 Value: &bazel.Label{
1097 Label: ":" + ccAidlLibrarylabel,
1098 },
1099 }
1100 return label
1101 }
1102
Vinh Trana3b8b782022-09-14 11:40:24 -04001103 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -04001104}
1105
Yu Liufc603162022-03-01 15:44:08 -08001106func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +00001107 return sdkAttributes{
1108 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -08001109 Min_sdk_version: module.Properties.Min_sdk_version,
1110 }
1111}
1112
1113type sdkAttributes struct {
1114 Sdk_version *string
1115 Min_sdk_version *string
1116}
1117
Jingwen Chen107c0de2021-04-09 10:43:12 +00001118// Convenience struct to hold all attributes parsed from linker properties.
1119type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -05001120 deps bazel.LabelListAttribute
1121 implementationDeps bazel.LabelListAttribute
1122 dynamicDeps bazel.LabelListAttribute
1123 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -07001124 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -05001125 wholeArchiveDeps bazel.LabelListAttribute
1126 implementationWholeArchiveDeps bazel.LabelListAttribute
1127 systemDynamicDeps bazel.LabelListAttribute
1128 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -04001129
Rupert Shuttleworth484aa252021-12-10 07:22:53 -05001130 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001131 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -04001132 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001133 stripKeepSymbols bazel.BoolAttribute
1134 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
1135 stripKeepSymbolsList bazel.StringListAttribute
1136 stripAll bazel.BoolAttribute
1137 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -04001138 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -04001139}
1140
Liz Kammer54309532021-12-14 12:21:22 -05001141var (
1142 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -04001143 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -05001144)
1145
Vinh Tran85fb07c2022-09-16 16:17:48 -04001146// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
1147// since all libs are already excluded by default
Liz Kammer748d7072023-01-25 12:07:43 -05001148func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, props *BaseLinkerProperties) {
1149 excludeSharedLibs := bazelLabelForSharedDeps(ctx, props.Target.Apex.Exclude_shared_libs)
1150 sharedExcludes := bazel.LabelList{Excludes: excludeSharedLibs.Includes}
1151 sharedExcludesLabelList := bazel.LabelListAttribute{}
1152 sharedExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, sharedExcludes)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001153
Liz Kammer748d7072023-01-25 12:07:43 -05001154 la.dynamicDeps.Append(sharedExcludesLabelList)
1155 la.implementationDynamicDeps.Append(sharedExcludesLabelList)
1156
1157 excludeStaticLibs := bazelLabelForStaticDeps(ctx, props.Target.Apex.Exclude_static_libs)
1158 staticExcludes := bazel.LabelList{Excludes: excludeStaticLibs.Includes}
1159 staticExcludesLabelList := bazel.LabelListAttribute{}
1160 staticExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, staticExcludes)
1161
1162 la.deps.Append(staticExcludesLabelList)
1163 la.implementationDeps.Append(staticExcludesLabelList)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001164}
1165
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001166func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, module *Module, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
1167 isBinary := module.Binary()
Liz Kammere6583482021-10-19 13:56:10 -04001168 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
1169 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -04001170
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001171 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -04001172 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
1173 if axis == bazel.NoConfigAxis {
1174 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
1175 if proptools.Bool(props.Use_version_lib) {
1176 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
1177 // remove from static libs so there is no duplicate dependency
1178 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
1179 // only add the dep if it is not in progress
1180 if !versionLibAlreadyInDeps {
Yu Liufe978fd2023-04-24 16:37:18 -07001181 wholeStaticLibs = append(wholeStaticLibs, versionLib)
Liz Kammerbaced712022-09-16 09:01:29 -04001182 }
1183 }
1184 }
1185
Liz Kammere6583482021-10-19 13:56:10 -04001186 // Excludes to parallel Soong:
1187 // 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 -04001188 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001189
Vinh Tran85fb07c2022-09-16 16:17:48 -04001190 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1191 ctx,
1192 !isBinary,
1193 staticLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001194 props.Exclude_static_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001195 props.Export_static_lib_headers,
1196 bazelLabelForStaticDepsExcludes,
1197 )
Liz Kammer7a210ac2021-09-22 15:52:58 -04001198
Liz Kammere6583482021-10-19 13:56:10 -04001199 headerLibs := android.FirstUniqueStrings(props.Header_libs)
1200 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -04001201
Liz Kammere6583482021-10-19 13:56:10 -04001202 (&hDeps.export).Append(staticDeps.export)
1203 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001204
Liz Kammere6583482021-10-19 13:56:10 -04001205 (&hDeps.implementation).Append(staticDeps.implementation)
1206 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -04001207
Liz Kammere6583482021-10-19 13:56:10 -04001208 systemSharedLibs := props.System_shared_libs
1209 // systemSharedLibs distinguishes between nil/empty list behavior:
1210 // nil -> use default values
1211 // empty list -> no values specified
1212 if len(systemSharedLibs) > 0 {
1213 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
1214 }
1215 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
1216
1217 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -05001218 excludeSharedLibs := props.Exclude_shared_libs
1219 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
1220 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
1221 })
1222 for _, el := range usedSystem {
1223 if la.usedSystemDynamicDepAsDynamicDep == nil {
1224 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
1225 }
1226 la.usedSystemDynamicDepAsDynamicDep[el] = true
1227 }
1228
Vinh Tran85fb07c2022-09-16 16:17:48 -04001229 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1230 ctx,
1231 !isBinary,
1232 sharedLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001233 props.Exclude_shared_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001234 props.Export_shared_lib_headers,
1235 bazelLabelForSharedDepsExcludes,
1236 )
Liz Kammere6583482021-10-19 13:56:10 -04001237 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
1238 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Liz Kammer748d7072023-01-25 12:07:43 -05001239 la.resolveTargetApexProp(ctx, props)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001240
Wei Li81852ca2022-07-27 00:22:06 -07001241 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
Yu Liu10174ff2023-02-21 12:05:26 -08001242 // If a dependency in la.implementationDynamicDeps or la.dynamicDeps has stubs, its
1243 // stub variant should be used when the dependency is linked in a APEX. The
1244 // dependencies in NoConfigAxis and OsConfigurationAxis/OsAndroid are grouped by
1245 // having stubs or not, so Bazel select() statement can be used to choose
1246 // source/stub variants of them.
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001247 apexAvailable := module.ApexAvailable()
Spandan Dasac693b22023-04-24 00:07:38 +00001248 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.export, &la.dynamicDeps, 0, false)
1249 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.implementation, &la.implementationDynamicDeps, 1, false)
1250 if len(systemSharedLibs) > 0 {
1251 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, bazelLabelForSharedDeps(ctx, systemSharedLibs), &la.systemDynamicDeps, 2, true)
1252 }
Wei Li81852ca2022-07-27 00:22:06 -07001253 }
Liz Kammere6583482021-10-19 13:56:10 -04001254
1255 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1256 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1257 }
1258
1259 if Bool(props.Allow_undefined_symbols) {
1260 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1261 }
1262
1263 var linkerFlags []string
1264 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001265 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001266 // binaries remove static flag if -shared is in the linker flags
1267 if isBinary && android.InList("-shared", linkerFlags) {
1268 axisFeatures = append(axisFeatures, "-static_flag")
1269 }
1270 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001271
Alex Márquez Pérez Muñíz Díaz Puras Thaureaux01ec55e2023-01-30 22:53:04 +00001272 if !props.libCrt() {
1273 axisFeatures = append(axisFeatures, "-use_libcrt")
1274 }
1275 if !props.crt() {
1276 axisFeatures = append(axisFeatures, "-link_crt")
1277 }
1278
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001279 // This must happen before the addition of flags for Version Script and
1280 // Dynamic List, as these flags must be split on spaces and those must not
1281 linkerFlags = parseCommandLineFlags(linkerFlags, filterOutClangUnknownCflags)
1282
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001283 additionalLinkerInputs := bazel.LabelList{}
Liz Kammere6583482021-10-19 13:56:10 -04001284 if props.Version_script != nil {
1285 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001286 additionalLinkerInputs.Add(&label)
Liz Kammere6583482021-10-19 13:56:10 -04001287 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
Trevor Radcliffef06dd912023-05-19 14:51:41 +00001288 axisFeatures = append(axisFeatures, "android_cfi_exports_map")
Liz Kammere6583482021-10-19 13:56:10 -04001289 }
Alix773adaa2022-04-27 17:49:34 +00001290
1291 if props.Dynamic_list != nil {
1292 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001293 additionalLinkerInputs.Add(&label)
Alix773adaa2022-04-27 17:49:34 +00001294 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1295 }
1296
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001297 la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
Spandan Dasfb04c412023-05-15 18:35:36 +00001298 if axis == bazel.OsConfigurationAxis && (config == bazel.OsDarwin || config == bazel.OsLinux || config == bazel.OsWindows) {
1299 linkerFlags = append(linkerFlags, props.Host_ldlibs...)
1300 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001301 la.linkopts.SetSelectValue(axis, config, linkerFlags)
Liz Kammere6583482021-10-19 13:56:10 -04001302
1303 if axisFeatures != nil {
1304 la.features.SetSelectValue(axis, config, axisFeatures)
1305 }
Cole Faust6b29f592022-08-09 09:50:56 -07001306
1307 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1308 if !runtimeDeps.IsEmpty() {
1309 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1310 }
Liz Kammere6583482021-10-19 13:56:10 -04001311}
1312
Spandan Das2518c022023-03-17 03:02:32 +00001313var (
1314 apiSurfaceModuleLibCurrentPackage = "@api_surfaces//" + android.ModuleLibApi.String() + "/current:"
1315)
1316
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001317func availableToSameApexes(a, b []string) bool {
1318 if len(a) == 0 && len(b) == 0 {
1319 return true
1320 }
1321 differ, _, _ := android.ListSetDifference(a, b)
1322 return !differ
1323}
1324
Spandan Das4242f102023-04-19 22:31:54 +00001325var (
Spandan Das9cad90f2023-05-04 17:15:44 +00001326 apiDomainConfigSettingKey = android.NewOnceKey("apiDomainConfigSettingKey")
1327 apiDomainConfigSettingLock sync.Mutex
Spandan Das4242f102023-04-19 22:31:54 +00001328)
1329
Spandan Das9cad90f2023-05-04 17:15:44 +00001330func getApiDomainConfigSettingMap(config android.Config) *map[string]bool {
1331 return config.Once(apiDomainConfigSettingKey, func() interface{} {
Spandan Das4242f102023-04-19 22:31:54 +00001332 return &map[string]bool{}
1333 }).(*map[string]bool)
1334}
1335
Spandan Das9cad90f2023-05-04 17:15:44 +00001336var (
1337 testApexNameToApiDomain = map[string]string{
1338 "test_broken_com.android.art": "com.android.art",
1339 }
1340)
1341
Spandan Dasa43ae132023-05-08 18:33:16 +00001342// GetApiDomain returns the canonical name of the apex. This is synonymous to the apex_name definition.
1343// https://cs.android.com/android/_/android/platform/build/soong/+/e3f0281b8897da1fe23b2f4f3a05f1dc87bcc902:apex/prebuilt.go;l=81-83;drc=2dc7244af985a6ad701b22f1271e606cabba527f;bpv=1;bpt=0
1344// For test apexes, it uses a naming convention heuristic to determine the api domain.
1345// TODO (b/281548611): Move this build/soong/android
1346func GetApiDomain(apexName string) string {
Spandan Das9cad90f2023-05-04 17:15:44 +00001347 if apiDomain, exists := testApexNameToApiDomain[apexName]; exists {
1348 return apiDomain
1349 }
1350 // Remove `test_` prefix
1351 return strings.TrimPrefix(apexName, "test_")
1352}
1353
Spandan Das4242f102023-04-19 22:31:54 +00001354// Create a config setting for this apex in build/bazel/rules/apex
1355// The use case for this is stub/impl selection in cc libraries
1356// Long term, these config_setting(s) should be colocated with the respective apex definitions.
1357// Note that this is an anti-pattern: The config_setting should be created from the apex definition
1358// and not from a cc_library.
1359// This anti-pattern is needed today since not all apexes have been allowlisted.
1360func createInApexConfigSetting(ctx android.TopDownMutatorContext, apexName string) {
1361 if apexName == android.AvailableToPlatform || apexName == android.AvailableToAnyApex {
1362 // These correspond to android-non_apex and android-in_apex
1363 return
1364 }
Spandan Das9cad90f2023-05-04 17:15:44 +00001365 apiDomainConfigSettingLock.Lock()
1366 defer apiDomainConfigSettingLock.Unlock()
Spandan Das4242f102023-04-19 22:31:54 +00001367
1368 // Return if a config_setting has already been created
Spandan Dasa43ae132023-05-08 18:33:16 +00001369 apiDomain := GetApiDomain(apexName)
Spandan Das9cad90f2023-05-04 17:15:44 +00001370 acsm := getApiDomainConfigSettingMap(ctx.Config())
1371 if _, exists := (*acsm)[apiDomain]; exists {
Spandan Das4242f102023-04-19 22:31:54 +00001372 return
1373 }
Spandan Das9cad90f2023-05-04 17:15:44 +00001374 (*acsm)[apiDomain] = true
Spandan Das4242f102023-04-19 22:31:54 +00001375
1376 csa := bazel.ConfigSettingAttributes{
1377 Flag_values: bazel.StringMapAttribute{
Spandan Das9cad90f2023-05-04 17:15:44 +00001378 "//build/bazel/rules/apex:api_domain": apiDomain,
Spandan Das4242f102023-04-19 22:31:54 +00001379 },
Spandan Das9cad90f2023-05-04 17:15:44 +00001380 // Constraint this to android
1381 Constraint_values: bazel.MakeLabelListAttribute(
1382 bazel.MakeLabelList(
1383 []bazel.Label{
1384 bazel.Label{Label: "//build/bazel/platforms/os:android"},
1385 },
1386 ),
1387 ),
Spandan Das4242f102023-04-19 22:31:54 +00001388 }
1389 ca := android.CommonAttributes{
Spandan Das9cad90f2023-05-04 17:15:44 +00001390 Name: apiDomain,
Spandan Das4242f102023-04-19 22:31:54 +00001391 }
1392 ctx.CreateBazelConfigSetting(
1393 csa,
1394 ca,
1395 "build/bazel/rules/apex",
1396 )
1397}
1398
1399func inApexConfigSetting(apexAvailable string) string {
1400 if apexAvailable == android.AvailableToPlatform {
Spandan Das6d4d9da2023-04-18 06:20:40 +00001401 return bazel.AndroidPlatform
Spandan Das4242f102023-04-19 22:31:54 +00001402 }
1403 if apexAvailable == android.AvailableToAnyApex {
1404 return bazel.AndroidAndInApex
1405 }
Spandan Dasa43ae132023-05-08 18:33:16 +00001406 apiDomain := GetApiDomain(apexAvailable)
Spandan Das9cad90f2023-05-04 17:15:44 +00001407 return "//build/bazel/rules/apex:" + apiDomain
Spandan Das4242f102023-04-19 22:31:54 +00001408}
1409
Spandan Das6d4d9da2023-04-18 06:20:40 +00001410// Inputs to stub vs impl selection.
1411type stubSelectionInfo struct {
1412 // Label of the implementation library (e.g. //bionic/libc:libc)
1413 impl bazel.Label
1414 // Axis containing the implementation library
1415 axis bazel.ConfigurationAxis
1416 // Axis key containing the implementation library
1417 config string
1418 // API domain of the apex
1419 // For test apexes (test_com.android.foo), this will be the source apex (com.android.foo)
1420 apiDomain string
1421 // List of dep labels
1422 dynamicDeps *bazel.LabelListAttribute
1423 // Boolean value for determining if the dep is in the same api domain
1424 // If false, the label will be rewritten to to the stub label
1425 sameApiDomain bool
1426}
1427
1428func useStubOrImplInApexWithName(ssi stubSelectionInfo) {
1429 lib := ssi.impl
1430 if !ssi.sameApiDomain {
1431 lib = bazel.Label{
1432 Label: apiSurfaceModuleLibCurrentPackage + strings.TrimPrefix(lib.OriginalModuleName, ":"),
1433 }
1434 }
1435 // Create a select statement specific to this apex
1436 inApexSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain))
1437 (&inApexSelectValue).Append(bazel.MakeLabelList([]bazel.Label{lib}))
1438 ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain), bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1439 // Delete the library from the common config for this apex
1440 implDynamicDeps := ssi.dynamicDeps.SelectValue(ssi.axis, ssi.config)
1441 implDynamicDeps = bazel.SubtractBazelLabelList(implDynamicDeps, bazel.MakeLabelList([]bazel.Label{ssi.impl}))
1442 ssi.dynamicDeps.SetSelectValue(ssi.axis, ssi.config, implDynamicDeps)
1443 if ssi.axis == bazel.NoConfigAxis {
1444 // Set defaults. Defaults (i.e. host) should use impl and not stubs.
1445 defaultSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
1446 (&defaultSelectValue).Append(bazel.MakeLabelList([]bazel.Label{ssi.impl}))
1447 ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
1448 }
Liz Kammere6583482021-10-19 13:56:10 -04001449}
1450
Yu Liu10174ff2023-02-21 12:05:26 -08001451func setStubsForDynamicDeps(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis,
Spandan Dasac693b22023-04-24 00:07:38 +00001452 config string, apexAvailable []string, dynamicLibs bazel.LabelList, dynamicDeps *bazel.LabelListAttribute, ind int, buildNonApexWithStubs bool) {
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001453
Spandan Das4242f102023-04-19 22:31:54 +00001454 // Create a config_setting for each apex_available.
1455 // This will be used to select impl of a dep if dep is available to the same apex.
1456 for _, aa := range apexAvailable {
1457 createInApexConfigSetting(ctx.(android.TopDownMutatorContext), aa)
1458 }
1459
Spandan Das6d4d9da2023-04-18 06:20:40 +00001460 apiDomainForSelects := []string{}
1461 for _, apex := range apexAvailable {
1462 apiDomainForSelects = append(apiDomainForSelects, GetApiDomain(apex))
1463 }
1464 // Always emit a select statement for the platform variant.
1465 // This ensures that b build //foo --config=android works
1466 // Soong always creates a platform variant even when the library might not be available to platform.
1467 if !android.InList(android.AvailableToPlatform, apiDomainForSelects) {
1468 apiDomainForSelects = append(apiDomainForSelects, android.AvailableToPlatform)
1469 }
1470 apiDomainForSelects = android.SortedUniqueStrings(apiDomainForSelects)
1471
1472 // Create a select for each apex this library could be included in.
1473 for _, l := range dynamicLibs.Includes {
1474 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
1475 if c, ok := dep.(*Module); !ok || !c.HasStubsVariants() {
1476 continue
1477 }
1478 // TODO (b/280339069): Decrease the verbosity of the generated BUILD files
1479 for _, apiDomain := range apiDomainForSelects {
1480 var sameApiDomain bool
1481 if apiDomain == android.AvailableToPlatform {
1482 // Platform variants in Soong use equality of apex_available for stub/impl selection.
1483 // https://cs.android.com/android/_/android/platform/build/soong/+/316b0158fe57ee7764235923e7c6f3d530da39c6:cc/cc.go;l=3393-3404;drc=176271a426496fa2688efe2b40d5c74340c63375;bpv=1;bpt=0
1484 // One of the factors behind this design choice is cc_test
1485 // Tests only have a platform variant, and using equality of apex_available ensures
1486 // that tests of an apex library gets its implementation and not stubs.
1487 // TODO (b/280343104): Discuss if we can drop this special handling for platform variants.
1488 sameApiDomain = availableToSameApexes(apexAvailable, dep.(*Module).ApexAvailable())
Spandan Das6aaab9d2023-05-04 17:27:30 +00001489 if linkable, ok := ctx.Module().(LinkableInterface); ok && linkable.Bootstrap() {
1490 sameApiDomain = true
1491 }
Spandan Das6d4d9da2023-04-18 06:20:40 +00001492 } else {
1493 sameApiDomain = android.InList(apiDomain, dep.(*Module).ApexAvailable())
1494 }
1495 ssi := stubSelectionInfo{
1496 impl: l,
1497 axis: axis,
1498 config: config,
1499 apiDomain: apiDomain,
1500 dynamicDeps: dynamicDeps,
1501 sameApiDomain: sameApiDomain,
1502 }
1503 useStubOrImplInApexWithName(ssi)
1504 }
1505 }
Yu Liu10174ff2023-02-21 12:05:26 -08001506}
1507
Jingwen Chen55bc8202021-11-02 06:40:51 +00001508func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001509 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1510 if stripProperties, ok := props.(*StripProperties); ok {
1511 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1512 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1513 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1514 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1515 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001516 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001517 })
Liz Kammere6583482021-10-19 13:56:10 -04001518}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001519
Jingwen Chen55bc8202021-11-02 06:40:51 +00001520func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001521
Liz Kammer47535c52021-06-02 16:02:22 -04001522 type productVarDep struct {
1523 // the name of the corresponding excludes field, if one exists
1524 excludesField string
1525 // reference to the bazel attribute that should be set for the given product variable config
1526 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001527
Jingwen Chen55bc8202021-11-02 06:40:51 +00001528 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001529 }
1530
Zi Wang0a8a1292022-08-30 06:27:01 +00001531 // an intermediate attribute that holds Header_libs info, and will be appended to
1532 // implementationDeps at the end, to solve the confliction that both header_libs
1533 // and static_libs use implementationDeps.
1534 var headerDeps bazel.LabelListAttribute
1535
Liz Kammer47535c52021-06-02 16:02:22 -04001536 productVarToDepFields := map[string]productVarDep{
1537 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001538 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1539 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1540 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001541 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001542 }
1543
Liz Kammer47535c52021-06-02 16:02:22 -04001544 for name, dep := range productVarToDepFields {
1545 props, exists := productVariableProps[name]
1546 excludeProps, excludesExists := productVariableProps[dep.excludesField]
Sasha Smundak39a301c2022-12-29 17:11:49 -08001547 // if neither an include nor excludes property exists, then skip it
Liz Kammer47535c52021-06-02 16:02:22 -04001548 if !exists && !excludesExists {
1549 continue
1550 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001551 // Collect all the configurations that an include or exclude property exists for.
1552 // We want to iterate all configurations rather than either the include or exclude because, for a
1553 // particular configuration, we may have either only an include or an exclude to handle.
Cole Faust150f9a52023-04-26 10:52:24 -07001554 productConfigProps := make(map[android.ProductConfigOrSoongConfigProperty]bool, len(props)+len(excludeProps))
Jingwen Chen25825ca2021-11-15 12:28:43 +00001555 for p := range props {
1556 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001557 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001558 for p := range excludeProps {
1559 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001560 }
1561
Jingwen Chen25825ca2021-11-15 12:28:43 +00001562 for productConfigProp := range productConfigProps {
1563 prop, includesExists := props[productConfigProp]
1564 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001565 var includes, excludes []string
1566 var ok bool
1567 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001568 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001569 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1570 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001571 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001572 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1573 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001574
Jingwen Chen58ff6802021-11-17 12:14:41 +00001575 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001576 dep.attribute.SetSelectValue(
1577 productConfigProp.ConfigurationAxis(),
1578 productConfigProp.SelectKey(),
1579 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1580 )
Liz Kammer47535c52021-06-02 16:02:22 -04001581 }
1582 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001583 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001584}
Liz Kammer47535c52021-06-02 16:02:22 -04001585
Liz Kammer54309532021-12-14 12:21:22 -05001586func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1587 // if system dynamic deps have the default value, any use of a system dynamic library used will
1588 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001589 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001590 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -08001591 toRemove := bazelLabelForSharedDeps(ctx, android.SortedKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001592 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001593 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1594 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001595 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001596 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1597 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001598
1599 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001600 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1601 for _, lib := range toRemove.Includes {
Spandan Das2518c022023-03-17 03:02:32 +00001602 stubLabelInApiSurfaces := bazel.Label{
1603 Label: apiSurfaceModuleLibCurrentPackage + lib.OriginalModuleName,
1604 }
1605 stubsToRemove = append(stubsToRemove, stubLabelInApiSurfaces)
Liz Kammer91487d42022-09-13 11:27:11 -04001606 }
Spandan Das6d4d9da2023-04-18 06:20:40 +00001607 // system libraries (e.g. libc, libm, libdl) belong the com.android.runtime api domain
1608 // dedupe the stubs of these libraries from the other api domains (platform, other_apexes...)
1609 for _, aa := range ctx.Module().(*Module).ApexAvailable() {
1610 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, inApexConfigSetting(aa), bazel.MakeLabelList(stubsToRemove))
1611 }
1612 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidPlatform, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001613 }
1614
Liz Kammere6583482021-10-19 13:56:10 -04001615 la.deps.ResolveExcludes()
1616 la.implementationDeps.ResolveExcludes()
1617 la.dynamicDeps.ResolveExcludes()
1618 la.implementationDynamicDeps.ResolveExcludes()
1619 la.wholeArchiveDeps.ResolveExcludes()
1620 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001621
Jingwen Chen91220d72021-03-24 02:18:33 -04001622}
1623
Jingwen Chened9c17d2021-04-13 07:14:55 +00001624// Relativize a list of root-relative paths with respect to the module's
1625// directory.
1626//
1627// include_dirs Soong prop are root-relative (b/183742505), but
1628// local_include_dirs, export_include_dirs and export_system_include_dirs are
1629// module dir relative. This function makes a list of paths entirely module dir
1630// relative.
1631//
1632// For the `include` attribute, Bazel wants the paths to be relative to the
1633// module.
1634func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001635 var relativePaths []string
1636 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001637 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1638 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1639 if err != nil {
1640 panic(err)
1641 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001642 relativePaths = append(relativePaths, relativePath)
1643 }
1644 return relativePaths
1645}
1646
Liz Kammer5fad5012021-09-09 14:08:21 -04001647// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1648// attributes.
1649type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001650 AbsoluteIncludes bazel.StringListAttribute
1651 Includes bazel.StringListAttribute
1652 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001653}
1654
Liz Kammer54549442022-05-11 13:55:06 -04001655func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001656 var exported BazelIncludes
1657 if includes != nil {
1658 exported = *includes
1659 } else {
1660 exported = BazelIncludes{}
1661 }
Zi Wang1cb11802022-12-09 16:08:54 -08001662
1663 // cc library Export_include_dirs and Export_system_include_dirs are marked
1664 // "variant_prepend" in struct tag, set their prepend property to true to make
1665 // sure bp2build generates correct result.
1666 exported.Includes.Prepend = true
1667 exported.SystemIncludes.Prepend = true
1668
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001669 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1670 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1671 if len(flagExporterProperties.Export_include_dirs) > 0 {
1672 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1673 }
1674 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1675 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 -04001676 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001677 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001678 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001679 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001680 exported.Includes.DeduplicateAxesFromBase()
1681 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001682
Liz Kammer5fad5012021-09-09 14:08:21 -04001683 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001684}
Chris Parsons953b3562021-09-20 15:14:39 -04001685
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001686func BazelLabelNameForStaticModule(baseLabel string) string {
1687 return baseLabel + "_bp2build_cc_library_static"
1688}
1689
Jingwen Chen55bc8202021-11-02 06:40:51 +00001690func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001691 label := android.BazelModuleLabel(ctx, m)
Sasha Smundak39a301c2022-12-29 17:11:49 -08001692 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001693 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001694 }
1695 return label
1696}
1697
Jingwen Chen55bc8202021-11-02 06:40:51 +00001698func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001699 // cc_library, at it's root name, propagates the shared library, which depends on the static
1700 // library.
1701 return android.BazelModuleLabel(ctx, m)
1702}
1703
Jingwen Chen55bc8202021-11-02 06:40:51 +00001704func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001705 label := bazelLabelForStaticModule(ctx, m)
1706 if aModule, ok := m.(android.Module); ok {
1707 if android.IsModulePrebuilt(aModule) {
1708 label += "_alwayslink"
1709 }
1710 }
1711 return label
1712}
1713
Liz Kammer084d6a92023-06-22 16:23:53 -04001714// Replaces //a/b/my_xsd_config with //a/b/my_xsd_config-cpp
1715func xsdConfigCppTarget(ctx android.BazelConversionPathContext, mod blueprint.Module) string {
1716 callback := func(xsd android.XsdConfigBp2buildTargets) string {
1717 return xsd.CppBp2buildTargetName()
1718 }
1719 return android.XsdConfigBp2buildTarget(ctx, mod, callback)
1720}
1721
1722func bazelLabelForXsdConfig(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
1723 return android.BazelLabelForModuleDepsWithFn(ctx, modules, xsdConfigCppTarget)
1724}
1725
Jingwen Chen55bc8202021-11-02 06:40:51 +00001726func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001727 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1728}
1729
Jingwen Chen55bc8202021-11-02 06:40:51 +00001730func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001731 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1732}
1733
Jingwen Chen55bc8202021-11-02 06:40:51 +00001734func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001735 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1736}
1737
Jingwen Chen55bc8202021-11-02 06:40:51 +00001738func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001739 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1740}
1741
Jingwen Chen55bc8202021-11-02 06:40:51 +00001742func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001743 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1744}
1745
Jingwen Chen55bc8202021-11-02 06:40:51 +00001746func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001747 // This is not elegant, but bp2build's shared library targets only propagate
1748 // their header information as part of the normal C++ provider.
1749 return bazelLabelForSharedDeps(ctx, modules)
1750}
1751
Zi Wang0a8a1292022-08-30 06:27:01 +00001752func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1753 // This is only used when product_variable header_libs is processed, to follow
1754 // the pattern of depResolutionFunc
1755 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1756}
1757
Jingwen Chen55bc8202021-11-02 06:40:51 +00001758func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001759 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1760}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001761
1762type binaryLinkerAttrs struct {
1763 Linkshared *bool
Spandan Das39ccf932023-05-26 18:03:39 +00001764 Stem bazel.StringAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001765 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001766}
1767
Jingwen Chen55bc8202021-11-02 06:40:51 +00001768func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001769 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001770 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1771 linkerProps := props.(*BinaryLinkerProperties)
1772 staticExecutable := linkerProps.Static_executable
1773 if axis == bazel.NoConfigAxis {
1774 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1775 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001776 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001777 } else if staticExecutable != nil {
1778 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1779 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1780 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001781 }
Spandan Das39ccf932023-05-26 18:03:39 +00001782 if stem := linkerProps.Stem; stem != nil {
1783 attrs.Stem.SetSelectValue(axis, config, stem)
1784 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001785 if suffix := linkerProps.Suffix; suffix != nil {
1786 attrs.Suffix.SetSelectValue(axis, config, suffix)
1787 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001788 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001789
1790 return attrs
1791}
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001792
1793func bp2buildSanitizerFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1794 sanitizerFeatures := bazel.StringListAttribute{}
1795 bp2BuildPropParseHelper(ctx, m, &SanitizeProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1796 var features []string
1797 if sanitizerProps, ok := props.(*SanitizeProperties); ok {
1798 if sanitizerProps.Sanitize.Integer_overflow != nil && *sanitizerProps.Sanitize.Integer_overflow {
1799 features = append(features, "ubsan_integer_overflow")
1800 }
1801 for _, sanitizer := range sanitizerProps.Sanitize.Misc_undefined {
1802 features = append(features, "ubsan_"+sanitizer)
1803 }
Trevor Radcliffeded095c2023-06-12 19:18:28 +00001804 blocklist := sanitizerProps.Sanitize.Blocklist
1805 if blocklist != nil {
1806 // Format the blocklist name to be used in a feature name
1807 blocklistFeatureSuffix := strings.Replace(strings.ToLower(*blocklist), ".", "_", -1)
1808 features = append(features, "ubsan_blocklist_"+blocklistFeatureSuffix)
1809 }
Trevor Radcliffe27669c02023-03-28 20:47:10 +00001810 if proptools.Bool(sanitizerProps.Sanitize.Cfi) {
1811 features = append(features, "android_cfi")
1812 if proptools.Bool(sanitizerProps.Sanitize.Config.Cfi_assembly_support) {
1813 features = append(features, "android_cfi_assembly_support")
1814 }
1815 }
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001816 sanitizerFeatures.SetSelectValue(axis, config, features)
1817 }
1818 })
1819 return sanitizerFeatures
1820}
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +00001821
1822func bp2buildLtoFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1823 lto_feature_name := "android_thin_lto"
1824 ltoBoolFeatures := bazel.BoolAttribute{}
1825 bp2BuildPropParseHelper(ctx, m, &LTOProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1826 if ltoProps, ok := props.(*LTOProperties); ok {
1827 thinProp := ltoProps.Lto.Thin != nil && *ltoProps.Lto.Thin
1828 thinPropSetToFalse := ltoProps.Lto.Thin != nil && !*ltoProps.Lto.Thin
1829 neverProp := ltoProps.Lto.Never != nil && *ltoProps.Lto.Never
1830 if thinProp {
1831 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(true))
1832 return
1833 }
1834 if neverProp || thinPropSetToFalse {
1835 if thinProp {
1836 ctx.ModuleErrorf("lto.thin and lto.never are mutually exclusive but were specified together")
1837 } else {
1838 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(false))
1839 }
1840 return
1841 }
1842 }
1843 ltoBoolFeatures.SetSelectValue(axis, config, nil)
1844 })
1845
1846 props := m.GetArchVariantProperties(ctx, &LTOProperties{})
1847 ltoStringFeatures, err := ltoBoolFeatures.ToStringListAttribute(func(boolPtr *bool, axis bazel.ConfigurationAxis, config string) []string {
1848 if boolPtr == nil {
1849 return []string{}
1850 }
1851 if !*boolPtr {
1852 return []string{"-" + lto_feature_name}
1853 }
1854 features := []string{lto_feature_name}
1855 if ltoProps, ok := props[axis][config].(*LTOProperties); ok {
1856 if ltoProps.Whole_program_vtables != nil && *ltoProps.Whole_program_vtables {
1857 features = append(features, "android_thin_lto_whole_program_vtables")
1858 }
1859 }
1860 return features
1861 })
1862 if err != nil {
1863 ctx.ModuleErrorf("Error processing LTO attributes: %s", err)
1864 }
1865 return ltoStringFeatures
1866}
Trevor Radcliffea8b44162023-04-14 18:25:24 +00001867
1868func convertHiddenVisibilityToFeatureBase(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1869 visibilityHiddenFeature := bazel.StringListAttribute{}
1870 bp2BuildPropParseHelper(ctx, m, &BaseCompilerProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1871 if baseCompilerProps, ok := props.(*BaseCompilerProperties); ok {
1872 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, baseCompilerProps.Cflags)
1873 }
1874 })
1875 return visibilityHiddenFeature
1876}
1877
1878func convertHiddenVisibilityToFeatureStaticOrShared(ctx android.BazelConversionPathContext, m *Module, isStatic bool) bazel.StringListAttribute {
1879 visibilityHiddenFeature := bazel.StringListAttribute{}
1880 if isStatic {
1881 bp2BuildPropParseHelper(ctx, m, &StaticProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1882 if staticProps, ok := props.(*StaticProperties); ok {
1883 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, staticProps.Static.Cflags)
1884 }
1885 })
1886 } else {
1887 bp2BuildPropParseHelper(ctx, m, &SharedProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1888 if sharedProps, ok := props.(*SharedProperties); ok {
1889 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, sharedProps.Shared.Cflags)
1890 }
1891 })
1892 }
1893
1894 return visibilityHiddenFeature
1895}
1896
1897func convertHiddenVisibilityToFeatureHelper(feature *bazel.StringListAttribute, axis bazel.ConfigurationAxis, configString string, cflags []string) {
1898 if inList(config.VisibilityHiddenFlag, cflags) {
1899 feature.SetSelectValue(axis, configString, []string{"visibility_hidden"})
1900 }
1901}