blob: 3bb00adee6f64e83b0248a6199b454f008a59388 [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"
Liz Kammer91487d42022-09-13 11:27:11 -040041
42 stubsSuffix = "_stub_libs_current"
Liz Kammerae3994e2021-10-19 09:45:48 -040043)
44
Liz Kammer2222c6b2021-05-24 15:41:47 -040045// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000046// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040047type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040048 Srcs bazel.LabelListAttribute
49 Srcs_c bazel.LabelListAttribute
50 Srcs_as bazel.LabelListAttribute
51 Srcs_aidl bazel.LabelListAttribute
52 Hdrs bazel.LabelListAttribute
53 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000054
Liz Kammer12615db2021-09-28 09:19:17 -040055 Deps bazel.LabelListAttribute
56 Implementation_deps bazel.LabelListAttribute
57 Dynamic_deps bazel.LabelListAttribute
58 Implementation_dynamic_deps bazel.LabelListAttribute
59 Whole_archive_deps bazel.LabelListAttribute
60 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070061 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040062
63 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050064
65 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080066
Yu Liuf01a0f02022-12-07 15:45:30 -080067 Native_coverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -070068
Liz Kammeraceec252023-03-24 09:46:36 -040069 Apex_available []string
70
Trevor Radcliffea8b44162023-04-14 18:25:24 +000071 Features bazel.StringListAttribute
72
Yu Liufc603162022-03-01 15:44:08 -080073 sdkAttributes
Sam Delmericofb3bb322022-10-21 10:42:24 -040074
75 tidyAttributes
76}
77
78type tidyAttributes struct {
Sam Delmerico63f0c932023-03-14 14:05:28 -040079 Tidy *string
Sam Delmericofb3bb322022-10-21 10:42:24 -040080 Tidy_flags []string
81 Tidy_checks []string
82 Tidy_checks_as_errors []string
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040083 Tidy_disabled_srcs bazel.LabelListAttribute
Sam Delmerico4c902d62022-11-02 14:17:15 -040084 Tidy_timeout_srcs bazel.LabelListAttribute
Sam Delmericofb3bb322022-10-21 10:42:24 -040085}
86
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040087func (m *Module) convertTidyAttributes(ctx android.BaseMutatorContext, moduleAttrs *tidyAttributes) {
Sam Delmericofb3bb322022-10-21 10:42:24 -040088 for _, f := range m.features {
89 if tidy, ok := f.(*tidyFeature); ok {
Sam Delmerico63f0c932023-03-14 14:05:28 -040090 var tidyAttr *string
91 if tidy.Properties.Tidy != nil {
92 if *tidy.Properties.Tidy {
93 tidyAttr = proptools.StringPtr("local")
94 } else {
95 tidyAttr = proptools.StringPtr("never")
96 }
97 }
98 moduleAttrs.Tidy = tidyAttr
Sam Delmericofb3bb322022-10-21 10:42:24 -040099 moduleAttrs.Tidy_flags = tidy.Properties.Tidy_flags
100 moduleAttrs.Tidy_checks = tidy.Properties.Tidy_checks
101 moduleAttrs.Tidy_checks_as_errors = tidy.Properties.Tidy_checks_as_errors
102 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400103
104 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400105 archVariantProps := m.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
106 for axis, configToProps := range archVariantProps {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800107 for cfg, _props := range configToProps {
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400108 if archProps, ok := _props.(*BaseCompilerProperties); ok {
109 archDisabledSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_disabled_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800110 moduleAttrs.Tidy_disabled_srcs.SetSelectValue(axis, cfg, archDisabledSrcs)
Sam Delmerico4c902d62022-11-02 14:17:15 -0400111 archTimeoutSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_timeout_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800112 moduleAttrs.Tidy_timeout_srcs.SetSelectValue(axis, cfg, archTimeoutSrcs)
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400113 }
114 }
Sam Delmericofb3bb322022-10-21 10:42:24 -0400115 }
Jingwen Chen53681ef2021-04-29 08:15:13 +0000116}
117
Sam Delmericoc7681022022-02-04 21:01:20 +0000118// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000119func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400120 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
121 // macro.
122 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -0400123 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
124
125 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -0400126 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -0400127 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
128 return labelStr, false
129 }
Yu Liu2aa806b2022-09-01 11:54:47 -0700130 // If the filegroup is already converted to aidl_library or proto_library,
131 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
132 fg, _ := m.(android.FileGroupAsLibrary)
133 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -0400134 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000135 }
Liz Kammer12615db2021-09-28 09:19:17 -0400136 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400137 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000138 }
139
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400140 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +0000141 labels := bazel.LabelPartitions{
142 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500143 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
144 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -0700145 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -0400146 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000147 // TODO(http://b/231968910): If there is ever a filegroup target that
148 // contains .l or .ll files we will need to find a way to add a
149 // LabelMapper for these that identifies these filegroups and
150 // converts them appropriately
151 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
152 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400153 // C++ is the "catch-all" group, and comprises generated sources because we don't
154 // know the language of these sources until the genrule is executed.
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000155 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
156 syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
Sam Delmericoc7681022022-02-04 21:01:20 +0000157 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000158
Sam Delmericoc7681022022-02-04 21:01:20 +0000159 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000160}
161
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000162// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000163func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000164 lib, ok := module.compiler.(*libraryDecorator)
165 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400166 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000167 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000168 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
169}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000170
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000171// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000172func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000173 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000174}
175
176// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000177func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000178 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400179}
180
Liz Kammer7a210ac2021-09-22 15:52:58 -0400181type depsPartition struct {
182 export bazel.LabelList
183 implementation bazel.LabelList
184}
185
Jingwen Chen55bc8202021-11-02 06:40:51 +0000186type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400187
Jingwen Chen55bc8202021-11-02 06:40:51 +0000188func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400189 if !exportsDeps {
190 return depsPartition{
191 implementation: fn(ctx, allDeps),
192 }
193 }
194
Liz Kammer7a210ac2021-09-22 15:52:58 -0400195 implementation, export := android.FilterList(allDeps, exportedDeps)
196
197 return depsPartition{
198 export: fn(ctx, export),
199 implementation: fn(ctx, implementation),
200 }
201}
202
Jingwen Chen55bc8202021-11-02 06:40:51 +0000203type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400204
Jingwen Chen55bc8202021-11-02 06:40:51 +0000205func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400206 if !exportsDeps {
207 return depsPartition{
208 implementation: fn(ctx, allDeps, excludes),
209 }
210 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400211 implementation, export := android.FilterList(allDeps, exportedDeps)
212
213 return depsPartition{
214 export: fn(ctx, export, excludes),
215 implementation: fn(ctx, implementation, excludes),
216 }
217}
218
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000219func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
220 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800221 for cfg, props := range configToProps {
222 parseFunc(axis, cfg, props)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000223 }
224 }
225}
226
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000227// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Liz Kammeraceec252023-03-24 09:46:36 -0400228func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400229 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000230
Liz Kammer9abd62d2021-05-21 08:37:59 -0400231 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000232 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutHiddenVisibility))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000233 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400234 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400235
Liz Kammer2b8004b2021-10-04 13:55:44 -0400236 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400237 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
238 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
239
Liz Kammer2b8004b2021-10-04 13:55:44 -0400240 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400241 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
242 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
243
244 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500245 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000246 }
Liz Kammer135bf552021-08-11 10:46:06 -0400247 // system_dynamic_deps distinguishes between nil/empty list behavior:
248 // nil -> use default values
249 // empty list -> no values specified
250 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000251
Liz Kammeraceec252023-03-24 09:46:36 -0400252 var apexAvailable []string
Jingwen Chenbcf53042021-05-26 04:42:42 +0000253 if isStatic {
Liz Kammeraceec252023-03-24 09:46:36 -0400254 apexAvailable = lib.StaticProperties.Static.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000255 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
256 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
257 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000258 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000259 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000260 } else {
Liz Kammeraceec252023-03-24 09:46:36 -0400261 apexAvailable = lib.SharedProperties.Shared.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000262 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
263 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
264 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000265 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000266 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000267 }
268
Liz Kammerae3994e2021-10-19 09:45:48 -0400269 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
270 attrs.Srcs = partitionedSrcs[cppSrcPartition]
271 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
272 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000273
Spandan Das39b6cc52023-04-12 19:05:49 +0000274 attrs.Apex_available = android.ConvertApexAvailableToTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), apexAvailable)
Liz Kammeraceec252023-03-24 09:46:36 -0400275
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000276 attrs.Features.Append(convertHiddenVisibilityToFeatureStaticOrShared(ctx, module, isStatic))
277
Liz Kammer12615db2021-09-28 09:19:17 -0400278 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
279 // TODO(b/208815215): determine whether this is used and add support if necessary
280 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
281 }
282
Jingwen Chenbcf53042021-05-26 04:42:42 +0000283 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000284}
285
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400286// Convenience struct to hold all attributes parsed from prebuilt properties.
287type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000288 Src bazel.LabelAttribute
289 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400290}
291
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000292func parseSrc(ctx android.BazelConversionPathContext, srcLabelAttribute *bazel.LabelAttribute, axis bazel.ConfigurationAxis, config string, srcs []string) {
293 srcFileError := func() {
294 ctx.ModuleErrorf("parseSrc: Expected at most one source file for %s %s\n", axis, config)
295 }
296 if len(srcs) > 1 {
297 srcFileError()
298 return
299 } else if len(srcs) == 0 {
300 return
301 }
302 if srcLabelAttribute.SelectValue(axis, config) != nil {
303 srcFileError()
304 return
305 }
306 srcLabelAttribute.SetSelectValue(axis, config, android.BazelLabelForModuleSrcSingle(ctx, srcs[0]))
307}
308
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000309// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000310func 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 +0000311
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400312 var srcLabelAttribute bazel.LabelAttribute
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000313 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
314 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000315 parseSrc(ctx, &srcLabelAttribute, axis, config, prebuiltLinkerProperties.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000316 }
317 })
318
319 var enabledLabelAttribute bazel.BoolAttribute
320 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
321 if props.Enabled != nil {
322 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
323 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000324 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000325 }
326
327 if isStatic {
328 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
329 if staticProperties, ok := props.(*StaticProperties); ok {
330 parseAttrs(axis, config, staticProperties.Static)
331 }
332 })
333 } else {
334 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
335 if sharedProperties, ok := props.(*SharedProperties); ok {
336 parseAttrs(axis, config, sharedProperties.Shared)
337 }
338 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400339 }
340
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400341 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000342 Src: srcLabelAttribute,
343 Enabled: enabledLabelAttribute,
344 }
345}
346
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000347func bp2BuildParsePrebuiltBinaryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
348 var srcLabelAttribute bazel.LabelAttribute
349 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
350 if props, ok := props.(*prebuiltLinkerProperties); ok {
351 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000352 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000353 })
354
355 return prebuiltAttributes{
356 Src: srcLabelAttribute,
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400357 }
358}
359
Colin Crossc5075e92022-12-05 16:46:39 -0800360func bp2BuildParsePrebuiltObjectProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
361 var srcLabelAttribute bazel.LabelAttribute
362 bp2BuildPropParseHelper(ctx, module, &prebuiltObjectProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
363 if props, ok := props.(*prebuiltObjectProperties); ok {
364 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
365 }
366 })
367
368 return prebuiltAttributes{
369 Src: srcLabelAttribute,
370 }
371}
372
Liz Kammere6583482021-10-19 13:56:10 -0400373type baseAttributes struct {
374 compilerAttributes
375 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400376
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000377 // A combination of compilerAttributes.features and linkerAttributes.features, as well as sanitizer features
Cole Faust5fa4e962022-08-22 14:31:04 -0700378 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400379 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400380 aidlDependency *bazel.LabelAttribute
Yu Liuf01a0f02022-12-07 15:45:30 -0800381 Native_coverage *bool
Liz Kammere6583482021-10-19 13:56:10 -0400382}
383
Jingwen Chen107c0de2021-04-09 10:43:12 +0000384// Convenience struct to hold all attributes parsed from compiler properties.
385type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400386 // Options for all languages
387 copts bazel.StringListAttribute
388 // Assembly options and sources
389 asFlags bazel.StringListAttribute
390 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700391 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400392 // C options and sources
393 conlyFlags bazel.StringListAttribute
394 cSrcs bazel.LabelListAttribute
395 // C++ options and sources
396 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000397 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400398
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000399 // Lex sources and options
400 lSrcs bazel.LabelListAttribute
401 llSrcs bazel.LabelListAttribute
402 lexopts bazel.StringListAttribute
403
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000404 // Sysprop sources
405 syspropSrcs bazel.LabelListAttribute
406
Liz Kammere6583482021-10-19 13:56:10 -0400407 hdrs bazel.LabelListAttribute
408
Chris Parsons2c788392021-08-10 11:58:07 -0400409 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000410
411 // Not affected by arch variants
412 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500413 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000414 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400415
416 localIncludes bazel.StringListAttribute
417 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400418
Liz Kammer1263d9b2021-12-10 14:28:20 -0500419 includes BazelIncludes
420
Liz Kammer12615db2021-09-28 09:19:17 -0400421 protoSrcs bazel.LabelListAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400422 aidlSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000423
424 stubsSymbolFile *string
425 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700426
427 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500428
429 suffix bazel.StringAttribute
Vinh Tran99270ea2022-11-28 11:15:23 -0500430
431 fdoProfile bazel.LabelAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000432}
433
Liz Kammercac7f692021-12-16 14:19:32 -0500434type filterOutFn func(string) bool
435
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000436// filterOutHiddenVisibility removes the flag specifying hidden visibility as
437// this flag is converted to a toolchain feature
438func filterOutHiddenVisibility(flag string) bool {
439 return flag == config.VisibilityHiddenFlag
440}
441
Liz Kammercac7f692021-12-16 14:19:32 -0500442func filterOutStdFlag(flag string) bool {
443 return strings.HasPrefix(flag, "-std=")
444}
445
Alix1be00d42022-05-16 22:56:04 +0000446func filterOutClangUnknownCflags(flag string) bool {
447 for _, f := range config.ClangUnknownCflags {
448 if f == flag {
449 return true
450 }
451 }
452 return false
453}
454
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000455func parseCommandLineFlags(soongFlags []string, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400456 var result []string
457 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000458 skipFlag := false
459 for _, filter := range filterOut {
460 if filter != nil && filter(flag) {
461 skipFlag = true
462 }
463 }
464 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500465 continue
466 }
Liz Kammere6583482021-10-19 13:56:10 -0400467 // Soong's cflags can contain spaces, like `-include header.h`. For
468 // Bazel's copts, split them up to be compatible with the
469 // no_copts_tokenization feature.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000470 result = append(result, strings.Split(flag, " ")...)
Liz Kammere6583482021-10-19 13:56:10 -0400471 }
472 return result
473}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000474
Jingwen Chen55bc8202021-11-02 06:40:51 +0000475func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400476 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
477 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
478 if srcsList, ok := parseSrcs(ctx, props); ok {
479 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400480 }
481
Liz Kammere6583482021-10-19 13:56:10 -0400482 localIncludeDirs := props.Local_include_dirs
483 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500484 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400485 if includeBuildDirectory(props.Include_build_directory) {
486 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400487 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000488 }
489
Liz Kammere6583482021-10-19 13:56:10 -0400490 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
491 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
492
Cole Faust5fa4e962022-08-22 14:31:04 -0700493 instructionSet := proptools.StringDefault(props.Instruction_set, "")
494 if instructionSet == "arm" {
495 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm", "-arm_isa_thumb"})
496 } else if instructionSet != "" && instructionSet != "thumb" {
497 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
498 }
499
Liz Kammercac7f692021-12-16 14:19:32 -0500500 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
501 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
502 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
503 // cases.
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000504 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutClangUnknownCflags, filterOutHiddenVisibility))
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000505 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
506 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, filterOutClangUnknownCflags))
507 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400508 ca.rtti.SetSelectValue(axis, config, props.Rtti)
509}
510
Jingwen Chen55bc8202021-11-02 06:40:51 +0000511func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000512 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
513 if stlProps, ok := props.(*StlProperties); ok {
514 if stlProps.Stl == nil {
515 return
516 }
517 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400518 stl := deduplicateStlInput(*stlProps.Stl)
519 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000520 } else if ca.stl != stlProps.Stl {
521 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 -0400522 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000523 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000524 })
Liz Kammere6583482021-10-19 13:56:10 -0400525}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000526
Jingwen Chen55bc8202021-11-02 06:40:51 +0000527func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400528 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400529 "Cflags": &ca.copts,
530 "Asflags": &ca.asFlags,
Yu Liu93893ba2023-05-01 13:49:52 -0700531 "Cppflags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400532 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400533 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000534 if productConfigProps, exists := productVariableProps[propName]; exists {
535 for productConfigProp, prop := range productConfigProps {
536 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400537 if !ok {
538 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
539 }
Cole Faust150f9a52023-04-26 10:52:24 -0700540 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name())
Jingwen Chen25825ca2021-11-15 12:28:43 +0000541 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400542 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400543 }
544 }
Liz Kammere6583482021-10-19 13:56:10 -0400545}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400546
Jingwen Chen55bc8202021-11-02 06:40:51 +0000547func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400548 ca.srcs.ResolveExcludes()
549 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
550
Liz Kammer12615db2021-09-28 09:19:17 -0400551 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400552 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400553
Liz Kammere6583482021-10-19 13:56:10 -0400554 for p, lla := range partitionedSrcs {
555 // if there are no sources, there is no need for headers
556 if lla.IsEmpty() {
557 continue
558 }
559 lla.Append(implementationHdrs)
560 partitionedSrcs[p] = lla
561 }
562
563 ca.srcs = partitionedSrcs[cppSrcPartition]
564 ca.cSrcs = partitionedSrcs[cSrcPartition]
565 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700566 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000567 ca.lSrcs = partitionedSrcs[lSrcPartition]
568 ca.llSrcs = partitionedSrcs[llSrcPartition]
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000569 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400570
571 ca.absoluteIncludes.DeduplicateAxesFromBase()
572 ca.localIncludes.DeduplicateAxesFromBase()
573}
574
575// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000576func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400577 anySrcs := false
578 // Add srcs-like dependencies such as generated files.
579 // First create a LabelList containing these dependencies, then merge the values with srcs.
580 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
581 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
582 anySrcs = true
583 }
584
585 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400586
Liz Kammere6583482021-10-19 13:56:10 -0400587 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
588 anySrcs = true
589 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400590
Liz Kammere6583482021-10-19 13:56:10 -0400591 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
592}
593
Liz Kammera5a29de2022-05-25 23:19:37 -0400594func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
595 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500596 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
597 // Defaults are handled by the toolchain definition.
598 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400599 stdVal := proptools.StringDefault(std, defaultVal)
600 if stdVal == "experimental" || stdVal == defaultVal {
601 if stdVal == "experimental" {
602 stdVal = prefix + "_std_experimental"
603 }
604 if !useGnu {
605 stdVal += "_no_gnu"
606 }
607 } else if !useGnu {
608 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500609 }
610
Liz Kammera5a29de2022-05-25 23:19:37 -0400611 if stdVal == defaultVal {
612 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500613 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400614 return &stdVal
615}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500616
Liz Kammera5a29de2022-05-25 23:19:37 -0400617func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
618 useGnu := useGnuExtensions(gnu_extensions)
619
620 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400621}
622
Liz Kammer1263d9b2021-12-10 14:28:20 -0500623// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
624// is fully-qualified.
625// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
626func packageFromLabel(label string) (string, bool) {
627 split := strings.Split(label, ":")
628 if len(split) != 2 {
629 return "", false
630 }
631 if split[0] == "" {
632 return ".", false
633 }
634 // remove leading "//"
635 return split[0][2:], true
636}
637
638// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
639func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
640 for _, hdr := range labelList.Includes {
641 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
642 absolute = append(absolute, pkg)
643 } else if pkg != "" {
644 relative = append(relative, pkg)
645 }
646 }
647 return relative, absolute
648}
649
Cole Faust7071a052022-07-29 15:58:33 -0700650type YasmAttributes struct {
651 Srcs bazel.LabelListAttribute
652 Flags bazel.StringListAttribute
653 Include_dirs bazel.StringListAttribute
654}
655
656func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
657 if ca.asmSrcs.IsEmpty() {
658 return nil
659 }
660
661 // Yasm needs the include directories from both local_includes and
662 // export_include_dirs. We don't care about actually exporting them from the
663 // yasm rule though, because they will also be present on the cc_ rule that
664 // wraps this yasm rule.
665 includes := ca.localIncludes.Clone()
666 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
667 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
668 if len(flagExporterProperties.Export_include_dirs) > 0 {
669 x := bazel.StringListAttribute{}
670 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
671 includes.Append(x)
672 }
673 }
674 })
675
676 ctx.CreateBazelTargetModule(
677 bazel.BazelTargetModuleProperties{
678 Rule_class: "yasm",
679 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
680 },
681 android.CommonAttributes{Name: m.Name() + "_yasm"},
682 &YasmAttributes{
683 Srcs: ca.asmSrcs,
684 Flags: ca.asFlags,
685 Include_dirs: *includes,
686 })
687
688 // We only want to add a dependency on the _yasm target if there are asm
689 // sources in the current configuration. If there are unconfigured asm
690 // sources, always add the dependency. Otherwise, add the dependency only
691 // on the configuration axes and values that had asm sources.
692 if len(ca.asmSrcs.Value.Includes) > 0 {
693 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
694 }
695
696 ret := &bazel.LabelAttribute{}
697 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800698 for cfg := range ca.asmSrcs.ConfigurableValues[axis] {
699 ret.SetSelectValue(axis, cfg, bazel.Label{Label: ":" + m.Name() + "_yasm"})
Cole Faust7071a052022-07-29 15:58:33 -0700700 }
701 }
702 return ret
703}
704
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000705// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400706func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400707 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
708 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000709 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400710
711 var implementationHdrs bazel.LabelListAttribute
712
713 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
714 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
715 for axis, configMap := range cp {
716 if _, ok := axisToConfigs[axis]; !ok {
717 axisToConfigs[axis] = map[string]bool{}
718 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800719 for cfg := range configMap {
720 axisToConfigs[axis][cfg] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400721 }
722 }
723 }
Liz Kammere6583482021-10-19 13:56:10 -0400724 allAxesAndConfigs(archVariantCompilerProps)
725 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000726 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400727
Liz Kammere6583482021-10-19 13:56:10 -0400728 compilerAttrs := compilerAttributes{}
729 linkerAttrs := linkerAttributes{}
730
Chris Parsons7b3289b2023-01-26 17:30:44 -0500731 // Iterate through these axes in a deterministic order. This is required
732 // because processing certain dependencies may result in concatenating
733 // elements along other axes. (For example, processing NoConfig may result
734 // in elements being added to InApex). This is thus the only way to ensure
735 // that the order of entries in each list is in a predictable order.
736 for _, axis := range bazel.SortedConfigurationAxes(axisToConfigs) {
737 configs := axisToConfigs[axis]
Sasha Smundak39a301c2022-12-29 17:11:49 -0800738 for cfg := range configs {
Liz Kammere6583482021-10-19 13:56:10 -0400739 var allHdrs []string
Sasha Smundak39a301c2022-12-29 17:11:49 -0800740 if baseCompilerProps, ok := archVariantCompilerProps[axis][cfg].(*BaseCompilerProperties); ok {
Liz Kammere6583482021-10-19 13:56:10 -0400741 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000742 if baseCompilerProps.Lex != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800743 compilerAttrs.lexopts.SetSelectValue(axis, cfg, baseCompilerProps.Lex.Flags)
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000744 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800745 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, cfg, baseCompilerProps)
Liz Kammere6583482021-10-19 13:56:10 -0400746 }
747
748 var exportHdrs []string
749
Sasha Smundak39a301c2022-12-29 17:11:49 -0800750 if baseLinkerProps, ok := archVariantLinkerProps[axis][cfg].(*BaseLinkerProperties); ok {
Liz Kammere6583482021-10-19 13:56:10 -0400751 exportHdrs = baseLinkerProps.Export_generated_headers
752
Liz Kammer48cdbeb2023-03-17 10:17:50 -0400753 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module, axis, cfg, baseLinkerProps)
Liz Kammere6583482021-10-19 13:56:10 -0400754 }
755 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800756 implementationHdrs.SetSelectValue(axis, cfg, headers.implementation)
757 compilerAttrs.hdrs.SetSelectValue(axis, cfg, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500758
759 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800760 compilerAttrs.includes.Includes.SetSelectValue(axis, cfg, exportIncludes)
761 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, cfg, exportAbsoluteIncludes)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500762
763 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800764 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, cfg)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500765 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400766
Sasha Smundak39a301c2022-12-29 17:11:49 -0800767 compilerAttrs.absoluteIncludes.SetSelectValue(axis, cfg, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400768
Sasha Smundak39a301c2022-12-29 17:11:49 -0800769 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, cfg)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500770 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400771
Sasha Smundak39a301c2022-12-29 17:11:49 -0800772 compilerAttrs.localIncludes.SetSelectValue(axis, cfg, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000773
Sasha Smundak39a301c2022-12-29 17:11:49 -0800774 if libraryProps, ok := archVariantLibraryProperties[axis][cfg].(*LibraryProperties); ok {
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000775 if axis == bazel.NoConfigAxis {
Sam Delmerico75dbca22023-04-20 13:13:25 +0000776 if libraryProps.Stubs.Symbol_file != nil {
777 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
778 versions := android.CopyOf(libraryProps.Stubs.Versions)
779 normalizeVersions(ctx, versions)
780 versions = addCurrentVersionIfNotPresent(versions)
781 compilerAttrs.stubsVersions.SetSelectValue(axis, cfg, versions)
782 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000783 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500784 if suffix := libraryProps.Suffix; suffix != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800785 compilerAttrs.suffix.SetSelectValue(axis, cfg, suffix)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500786 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000787 }
Liz Kammere6583482021-10-19 13:56:10 -0400788 }
789 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400790
Liz Kammere6583482021-10-19 13:56:10 -0400791 compilerAttrs.convertStlProps(ctx, module)
792 (&linkerAttrs).convertStripProps(ctx, module)
793
Yu Liuf01a0f02022-12-07 15:45:30 -0800794 var nativeCoverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -0700795 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
796 !Bool(module.coverage.Properties.Native_coverage) {
Yu Liuf01a0f02022-12-07 15:45:30 -0800797 nativeCoverage = BoolPtr(false)
Yu Liu8d82ac52022-05-17 15:13:28 -0700798 }
799
Cole Faust912bc882023-03-08 12:29:50 -0800800 productVariableProps := android.ProductVariableProperties(ctx, ctx.Module())
Liz Kammere6583482021-10-19 13:56:10 -0400801
802 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
803 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
804
805 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500806 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400807
Cole Faust7071a052022-07-29 15:58:33 -0700808 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
809
Liz Kammer12615db2021-09-28 09:19:17 -0400810 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
811
812 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
813 // which. This will add the newly generated proto library to the appropriate attribute and nothing
814 // to the other
815 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
816 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400817
Vinh Tran395a1e92022-09-16 18:27:29 -0400818 aidlDep := bp2buildCcAidlLibrary(ctx, module, compilerAttrs.aidlSrcs, linkerAttrs)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400819 if aidlDep != nil {
820 if lib, ok := module.linker.(*libraryDecorator); ok {
821 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
822 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
823 } else {
824 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
825 }
826 }
827 }
Liz Kammer12615db2021-09-28 09:19:17 -0400828
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000829 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
830 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
831 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
832
Vinh Tran99270ea2022-11-28 11:15:23 -0500833 if module.afdo != nil && module.afdo.Properties.Afdo {
834 fdoProfileDep := bp2buildFdoProfile(ctx, module)
835 if fdoProfileDep != nil {
836 (&compilerAttrs).fdoProfile.SetValue(*fdoProfileDep)
837 }
838 }
839
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000840 if !compilerAttrs.syspropSrcs.IsEmpty() {
841 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
842 }
843
Zi Wang9f609db2023-01-04 11:06:54 -0800844 linkerAttrs.wholeArchiveDeps.Prepend = true
845 linkerAttrs.deps.Prepend = true
846 compilerAttrs.localIncludes.Prepend = true
847 compilerAttrs.absoluteIncludes.Prepend = true
848 compilerAttrs.hdrs.Prepend = true
849
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000850 features := compilerAttrs.features.Clone().Append(linkerAttrs.features).Append(bp2buildSanitizerFeatures(ctx, module))
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +0000851 features = features.Append(bp2buildLtoFeatures(ctx, module))
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000852 features = features.Append(convertHiddenVisibilityToFeatureBase(ctx, module))
Cole Faust5fa4e962022-08-22 14:31:04 -0700853 features.DeduplicateAxesFromBase()
854
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +0000855 addMuslSystemDynamicDeps(ctx, linkerAttrs)
856
Liz Kammere6583482021-10-19 13:56:10 -0400857 return baseAttributes{
858 compilerAttrs,
859 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700860 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400861 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400862 aidlDep,
Yu Liuf01a0f02022-12-07 15:45:30 -0800863 nativeCoverage,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000864 }
865}
866
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +0000867// As a workaround for b/261657184, we are manually adding the default value
868// of system_dynamic_deps for the linux_musl os.
869// TODO: Solve this properly
870func addMuslSystemDynamicDeps(ctx android.Bp2buildMutatorContext, attrs linkerAttributes) {
871 systemDynamicDeps := attrs.systemDynamicDeps.SelectValue(bazel.OsConfigurationAxis, "linux_musl")
872 if attrs.systemDynamicDeps.HasAxisSpecificValues(bazel.OsConfigurationAxis) && systemDynamicDeps.IsNil() {
873 attrs.systemDynamicDeps.SetSelectValue(bazel.OsConfigurationAxis, "linux_musl", android.BazelLabelForModuleDeps(ctx, config.MuslDefaultSharedLibraries))
874 }
875}
876
Vinh Tran99270ea2022-11-28 11:15:23 -0500877type fdoProfileAttributes struct {
878 Absolute_path_profile string
879}
880
881func bp2buildFdoProfile(
882 ctx android.Bp2buildMutatorContext,
883 m *Module,
884) *bazel.Label {
885 for _, project := range globalAfdoProfileProjects {
Vinh Tranbc9c8b42022-12-09 12:03:52 -0500886 // Ensure handcrafted BUILD file exists in the project
887 BUILDPath := android.ExistentPathForSource(ctx, project, "BUILD")
888 if BUILDPath.Valid() {
889 // We handcraft a BUILD file with fdo_profile targets that use the existing profiles in the project
890 // This implementation is assuming that every afdo profile in globalAfdoProfileProjects already has
891 // an associated fdo_profile target declared in the same package.
892 // TODO(b/260714900): Handle arch-specific afdo profiles (e.g. `<module-name>-arm<64>.afdo`)
893 path := android.ExistentPathForSource(ctx, project, m.Name()+".afdo")
894 if path.Valid() {
895 // FIXME: Some profiles only exist internally and are not released to AOSP.
896 // When generated BUILD files are checked in, we'll run into merge conflict.
897 // The cc_library_shared target in AOSP won't have reference to an fdo_profile target because
898 // the profile doesn't exist. Internally, the same cc_library_shared target will
899 // have reference to the fdo_profile.
900 // For more context, see b/258682955#comment2
901 fdoProfileLabel := "//" + strings.TrimSuffix(project, "/") + ":" + m.Name()
902 return &bazel.Label{
903 Label: fdoProfileLabel,
904 }
Vinh Tran99270ea2022-11-28 11:15:23 -0500905 }
906 }
907 }
908
909 return nil
910}
911
Vinh Tran9f6796a2022-08-16 13:10:31 -0400912func bp2buildCcAidlLibrary(
913 ctx android.Bp2buildMutatorContext,
914 m *Module,
Vinh Trana3b8b782022-09-14 11:40:24 -0400915 aidlLabelList bazel.LabelListAttribute,
Vinh Tran395a1e92022-09-16 18:27:29 -0400916 linkerAttrs linkerAttributes,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400917) *bazel.LabelAttribute {
Vinh Trana3b8b782022-09-14 11:40:24 -0400918 if !aidlLabelList.IsEmpty() {
919 aidlLibs, aidlSrcs := aidlLabelList.Partition(func(src bazel.Label) bool {
920 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
921 fg.ShouldConvertToAidlLibrary(ctx) {
922 return true
923 }
924 return false
925 })
Vinh Tran9f6796a2022-08-16 13:10:31 -0400926
Spandan Das39b6cc52023-04-12 19:05:49 +0000927 apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), ctx.Module())
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400928 sdkAttrs := bp2BuildParseSdkAttributes(m)
929
Vinh Trana3b8b782022-09-14 11:40:24 -0400930 if !aidlSrcs.IsEmpty() {
931 aidlLibName := m.Name() + "_aidl_library"
932 ctx.CreateBazelTargetModule(
933 bazel.BazelTargetModuleProperties{
934 Rule_class: "aidl_library",
Sam Delmericoe55bf082023-03-31 09:47:28 -0400935 Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
Vinh Trana3b8b782022-09-14 11:40:24 -0400936 },
937 android.CommonAttributes{Name: aidlLibName},
938 &aidlLibraryAttributes{
939 Srcs: aidlSrcs,
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400940 Tags: apexAvailableTags,
Vinh Trana3b8b782022-09-14 11:40:24 -0400941 },
942 )
943 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
944 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400945
Vinh Trana3b8b782022-09-14 11:40:24 -0400946 if !aidlLibs.IsEmpty() {
947 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
Sam Delmerico512437b2023-03-17 11:34:15 -0400948 // Since parent cc_library already has these dependencies, we can add them as implementation
949 // deps so that they don't re-export
950 implementationDeps := linkerAttrs.deps.Clone()
951 implementationDeps.Append(linkerAttrs.implementationDeps)
952 implementationDynamicDeps := linkerAttrs.dynamicDeps.Clone()
953 implementationDynamicDeps.Append(linkerAttrs.implementationDynamicDeps)
Vinh Tran395a1e92022-09-16 18:27:29 -0400954
Vinh Trana3b8b782022-09-14 11:40:24 -0400955 ctx.CreateBazelTargetModule(
956 bazel.BazelTargetModuleProperties{
957 Rule_class: "cc_aidl_library",
958 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
959 },
960 android.CommonAttributes{Name: ccAidlLibrarylabel},
961 &ccAidlLibraryAttributes{
Vinh Tran395a1e92022-09-16 18:27:29 -0400962 Deps: aidlLibs,
Sam Delmerico512437b2023-03-17 11:34:15 -0400963 Implementation_deps: *implementationDeps,
964 Implementation_dynamic_deps: *implementationDynamicDeps,
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400965 Tags: apexAvailableTags,
966 sdkAttributes: sdkAttrs,
Vinh Trana3b8b782022-09-14 11:40:24 -0400967 },
968 )
969 label := &bazel.LabelAttribute{
970 Value: &bazel.Label{
971 Label: ":" + ccAidlLibrarylabel,
972 },
973 }
974 return label
975 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400976 }
977
Vinh Trana3b8b782022-09-14 11:40:24 -0400978 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -0400979}
980
Yu Liufc603162022-03-01 15:44:08 -0800981func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000982 return sdkAttributes{
983 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800984 Min_sdk_version: module.Properties.Min_sdk_version,
985 }
986}
987
988type sdkAttributes struct {
989 Sdk_version *string
990 Min_sdk_version *string
991}
992
Jingwen Chen107c0de2021-04-09 10:43:12 +0000993// Convenience struct to hold all attributes parsed from linker properties.
994type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500995 deps bazel.LabelListAttribute
996 implementationDeps bazel.LabelListAttribute
997 dynamicDeps bazel.LabelListAttribute
998 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -0700999 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -05001000 wholeArchiveDeps bazel.LabelListAttribute
1001 implementationWholeArchiveDeps bazel.LabelListAttribute
1002 systemDynamicDeps bazel.LabelListAttribute
1003 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -04001004
Rupert Shuttleworth484aa252021-12-10 07:22:53 -05001005 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001006 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -04001007 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001008 stripKeepSymbols bazel.BoolAttribute
1009 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
1010 stripKeepSymbolsList bazel.StringListAttribute
1011 stripAll bazel.BoolAttribute
1012 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -04001013 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -04001014}
1015
Liz Kammer54309532021-12-14 12:21:22 -05001016var (
1017 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -04001018 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -05001019)
1020
Vinh Tran85fb07c2022-09-16 16:17:48 -04001021// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
1022// since all libs are already excluded by default
Liz Kammer748d7072023-01-25 12:07:43 -05001023func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, props *BaseLinkerProperties) {
1024 excludeSharedLibs := bazelLabelForSharedDeps(ctx, props.Target.Apex.Exclude_shared_libs)
1025 sharedExcludes := bazel.LabelList{Excludes: excludeSharedLibs.Includes}
1026 sharedExcludesLabelList := bazel.LabelListAttribute{}
1027 sharedExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, sharedExcludes)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001028
Liz Kammer748d7072023-01-25 12:07:43 -05001029 la.dynamicDeps.Append(sharedExcludesLabelList)
1030 la.implementationDynamicDeps.Append(sharedExcludesLabelList)
1031
1032 excludeStaticLibs := bazelLabelForStaticDeps(ctx, props.Target.Apex.Exclude_static_libs)
1033 staticExcludes := bazel.LabelList{Excludes: excludeStaticLibs.Includes}
1034 staticExcludesLabelList := bazel.LabelListAttribute{}
1035 staticExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, staticExcludes)
1036
1037 la.deps.Append(staticExcludesLabelList)
1038 la.implementationDeps.Append(staticExcludesLabelList)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001039}
1040
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001041func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, module *Module, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
1042 isBinary := module.Binary()
Liz Kammere6583482021-10-19 13:56:10 -04001043 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
1044 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -04001045
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001046 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -04001047 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
1048 if axis == bazel.NoConfigAxis {
1049 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
1050 if proptools.Bool(props.Use_version_lib) {
1051 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
1052 // remove from static libs so there is no duplicate dependency
1053 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
1054 // only add the dep if it is not in progress
1055 if !versionLibAlreadyInDeps {
Yu Liufe978fd2023-04-24 16:37:18 -07001056 wholeStaticLibs = append(wholeStaticLibs, versionLib)
Liz Kammerbaced712022-09-16 09:01:29 -04001057 }
1058 }
1059 }
1060
Liz Kammere6583482021-10-19 13:56:10 -04001061 // Excludes to parallel Soong:
1062 // 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 -04001063 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001064
Vinh Tran85fb07c2022-09-16 16:17:48 -04001065 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1066 ctx,
1067 !isBinary,
1068 staticLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001069 props.Exclude_static_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001070 props.Export_static_lib_headers,
1071 bazelLabelForStaticDepsExcludes,
1072 )
Liz Kammer7a210ac2021-09-22 15:52:58 -04001073
Liz Kammere6583482021-10-19 13:56:10 -04001074 headerLibs := android.FirstUniqueStrings(props.Header_libs)
1075 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -04001076
Liz Kammere6583482021-10-19 13:56:10 -04001077 (&hDeps.export).Append(staticDeps.export)
1078 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001079
Liz Kammere6583482021-10-19 13:56:10 -04001080 (&hDeps.implementation).Append(staticDeps.implementation)
1081 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -04001082
Liz Kammere6583482021-10-19 13:56:10 -04001083 systemSharedLibs := props.System_shared_libs
1084 // systemSharedLibs distinguishes between nil/empty list behavior:
1085 // nil -> use default values
1086 // empty list -> no values specified
1087 if len(systemSharedLibs) > 0 {
1088 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
1089 }
1090 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
1091
1092 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -05001093 excludeSharedLibs := props.Exclude_shared_libs
1094 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
1095 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
1096 })
1097 for _, el := range usedSystem {
1098 if la.usedSystemDynamicDepAsDynamicDep == nil {
1099 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
1100 }
1101 la.usedSystemDynamicDepAsDynamicDep[el] = true
1102 }
1103
Vinh Tran85fb07c2022-09-16 16:17:48 -04001104 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1105 ctx,
1106 !isBinary,
1107 sharedLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001108 props.Exclude_shared_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001109 props.Export_shared_lib_headers,
1110 bazelLabelForSharedDepsExcludes,
1111 )
Liz Kammere6583482021-10-19 13:56:10 -04001112 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
1113 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Liz Kammer748d7072023-01-25 12:07:43 -05001114 la.resolveTargetApexProp(ctx, props)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001115
Wei Li81852ca2022-07-27 00:22:06 -07001116 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
Yu Liu10174ff2023-02-21 12:05:26 -08001117 // If a dependency in la.implementationDynamicDeps or la.dynamicDeps has stubs, its
1118 // stub variant should be used when the dependency is linked in a APEX. The
1119 // dependencies in NoConfigAxis and OsConfigurationAxis/OsAndroid are grouped by
1120 // having stubs or not, so Bazel select() statement can be used to choose
1121 // source/stub variants of them.
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001122 apexAvailable := module.ApexAvailable()
Spandan Dasac693b22023-04-24 00:07:38 +00001123 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.export, &la.dynamicDeps, 0, false)
1124 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.implementation, &la.implementationDynamicDeps, 1, false)
1125 if len(systemSharedLibs) > 0 {
1126 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, bazelLabelForSharedDeps(ctx, systemSharedLibs), &la.systemDynamicDeps, 2, true)
1127 }
Wei Li81852ca2022-07-27 00:22:06 -07001128 }
Liz Kammere6583482021-10-19 13:56:10 -04001129
1130 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1131 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1132 }
1133
1134 if Bool(props.Allow_undefined_symbols) {
1135 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1136 }
1137
1138 var linkerFlags []string
1139 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001140 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001141 // binaries remove static flag if -shared is in the linker flags
1142 if isBinary && android.InList("-shared", linkerFlags) {
1143 axisFeatures = append(axisFeatures, "-static_flag")
1144 }
1145 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001146
Alex Márquez Pérez Muñíz Díaz Puras Thaureaux01ec55e2023-01-30 22:53:04 +00001147 if !props.libCrt() {
1148 axisFeatures = append(axisFeatures, "-use_libcrt")
1149 }
1150 if !props.crt() {
1151 axisFeatures = append(axisFeatures, "-link_crt")
1152 }
1153
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001154 // This must happen before the addition of flags for Version Script and
1155 // Dynamic List, as these flags must be split on spaces and those must not
1156 linkerFlags = parseCommandLineFlags(linkerFlags, filterOutClangUnknownCflags)
1157
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001158 additionalLinkerInputs := bazel.LabelList{}
Liz Kammere6583482021-10-19 13:56:10 -04001159 if props.Version_script != nil {
1160 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001161 additionalLinkerInputs.Add(&label)
Liz Kammere6583482021-10-19 13:56:10 -04001162 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
1163 }
Alix773adaa2022-04-27 17:49:34 +00001164
1165 if props.Dynamic_list != nil {
1166 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001167 additionalLinkerInputs.Add(&label)
Alix773adaa2022-04-27 17:49:34 +00001168 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1169 }
1170
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001171 la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001172 la.linkopts.SetSelectValue(axis, config, linkerFlags)
Liz Kammere6583482021-10-19 13:56:10 -04001173
1174 if axisFeatures != nil {
1175 la.features.SetSelectValue(axis, config, axisFeatures)
1176 }
Cole Faust6b29f592022-08-09 09:50:56 -07001177
1178 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1179 if !runtimeDeps.IsEmpty() {
1180 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1181 }
Liz Kammere6583482021-10-19 13:56:10 -04001182}
1183
Spandan Das2518c022023-03-17 03:02:32 +00001184var (
1185 apiSurfaceModuleLibCurrentPackage = "@api_surfaces//" + android.ModuleLibApi.String() + "/current:"
1186)
1187
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001188func availableToSameApexes(a, b []string) bool {
1189 if len(a) == 0 && len(b) == 0 {
1190 return true
1191 }
1192 differ, _, _ := android.ListSetDifference(a, b)
1193 return !differ
1194}
1195
Spandan Das4242f102023-04-19 22:31:54 +00001196var (
1197 apexConfigSettingKey = android.NewOnceKey("apexConfigSetting")
1198 apexConfigSettingLock sync.Mutex
1199)
1200
1201func getApexConfigSettingMap(config android.Config) *map[string]bool {
1202 return config.Once(apexConfigSettingKey, func() interface{} {
1203 return &map[string]bool{}
1204 }).(*map[string]bool)
1205}
1206
1207// Create a config setting for this apex in build/bazel/rules/apex
1208// The use case for this is stub/impl selection in cc libraries
1209// Long term, these config_setting(s) should be colocated with the respective apex definitions.
1210// Note that this is an anti-pattern: The config_setting should be created from the apex definition
1211// and not from a cc_library.
1212// This anti-pattern is needed today since not all apexes have been allowlisted.
1213func createInApexConfigSetting(ctx android.TopDownMutatorContext, apexName string) {
1214 if apexName == android.AvailableToPlatform || apexName == android.AvailableToAnyApex {
1215 // These correspond to android-non_apex and android-in_apex
1216 return
1217 }
1218 apexConfigSettingLock.Lock()
1219 defer apexConfigSettingLock.Unlock()
1220
1221 // Return if a config_setting has already been created
1222 acsm := getApexConfigSettingMap(ctx.Config())
1223 if _, exists := (*acsm)[apexName]; exists {
1224 return
1225 }
1226 (*acsm)[apexName] = true
1227
1228 csa := bazel.ConfigSettingAttributes{
1229 Flag_values: bazel.StringMapAttribute{
1230 "//build/bazel/rules/apex:apex_name": apexName,
1231 },
1232 }
1233 ca := android.CommonAttributes{
1234 Name: "android-in_" + apexName,
1235 }
1236 ctx.CreateBazelConfigSetting(
1237 csa,
1238 ca,
1239 "build/bazel/rules/apex",
1240 )
1241}
1242
1243func inApexConfigSetting(apexAvailable string) string {
1244 if apexAvailable == android.AvailableToPlatform {
1245 return bazel.AndroidAndNonApex
1246 }
1247 if apexAvailable == android.AvailableToAnyApex {
1248 return bazel.AndroidAndInApex
1249 }
1250 return "//build/bazel/rules/apex:android-in_" + apexAvailable
1251}
1252
Yu Liu10174ff2023-02-21 12:05:26 -08001253func setStubsForDynamicDeps(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis,
Spandan Dasac693b22023-04-24 00:07:38 +00001254 config string, apexAvailable []string, dynamicLibs bazel.LabelList, dynamicDeps *bazel.LabelListAttribute, ind int, buildNonApexWithStubs bool) {
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001255
Yu Liu10174ff2023-02-21 12:05:26 -08001256 depsWithStubs := []bazel.Label{}
1257 for _, l := range dynamicLibs.Includes {
1258 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001259 if d, ok := dep.(*Module); ok && d.HasStubsVariants() {
1260 depApexAvailable := d.ApexAvailable()
1261 if !availableToSameApexes(apexAvailable, depApexAvailable) {
1262 depsWithStubs = append(depsWithStubs, l)
1263 }
Yu Liu10174ff2023-02-21 12:05:26 -08001264 }
1265 }
1266 if len(depsWithStubs) > 0 {
1267 implDynamicDeps := bazel.SubtractBazelLabelList(dynamicLibs, bazel.MakeLabelList(depsWithStubs))
1268 dynamicDeps.SetSelectValue(axis, config, implDynamicDeps)
1269
1270 stubLibLabels := []bazel.Label{}
1271 for _, l := range depsWithStubs {
Spandan Das2518c022023-03-17 03:02:32 +00001272 stubLabelInApiSurfaces := bazel.Label{
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001273 Label: apiSurfaceModuleLibCurrentPackage + strings.TrimPrefix(l.OriginalModuleName, ":"),
Spandan Das2518c022023-03-17 03:02:32 +00001274 }
1275 stubLibLabels = append(stubLibLabels, stubLabelInApiSurfaces)
Yu Liu10174ff2023-02-21 12:05:26 -08001276 }
1277 inApexSelectValue := dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex)
1278 nonApexSelectValue := dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex)
1279 defaultSelectValue := dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
Spandan Dasac693b22023-04-24 00:07:38 +00001280 nonApexDeps := depsWithStubs
1281 if buildNonApexWithStubs {
1282 nonApexDeps = stubLibLabels
1283 }
Yu Liu10174ff2023-02-21 12:05:26 -08001284 if axis == bazel.NoConfigAxis {
1285 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
Spandan Dasac693b22023-04-24 00:07:38 +00001286 (&nonApexSelectValue).Append(bazel.MakeLabelList(nonApexDeps))
Yu Liu10174ff2023-02-21 12:05:26 -08001287 (&defaultSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
1288 dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1289 dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
1290 dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
1291 } else if config == bazel.OsAndroid {
1292 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
Spandan Dasac693b22023-04-24 00:07:38 +00001293 (&nonApexSelectValue).Append(bazel.MakeLabelList(nonApexDeps))
Yu Liu10174ff2023-02-21 12:05:26 -08001294 dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1295 dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
1296 }
1297 }
Spandan Das4242f102023-04-19 22:31:54 +00001298
1299 // Create a config_setting for each apex_available.
1300 // This will be used to select impl of a dep if dep is available to the same apex.
1301 for _, aa := range apexAvailable {
1302 createInApexConfigSetting(ctx.(android.TopDownMutatorContext), aa)
1303 }
1304
Yu Liu10174ff2023-02-21 12:05:26 -08001305}
1306
Jingwen Chen55bc8202021-11-02 06:40:51 +00001307func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001308 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1309 if stripProperties, ok := props.(*StripProperties); ok {
1310 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1311 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1312 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1313 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1314 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001315 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001316 })
Liz Kammere6583482021-10-19 13:56:10 -04001317}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001318
Jingwen Chen55bc8202021-11-02 06:40:51 +00001319func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001320
Liz Kammer47535c52021-06-02 16:02:22 -04001321 type productVarDep struct {
1322 // the name of the corresponding excludes field, if one exists
1323 excludesField string
1324 // reference to the bazel attribute that should be set for the given product variable config
1325 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001326
Jingwen Chen55bc8202021-11-02 06:40:51 +00001327 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001328 }
1329
Zi Wang0a8a1292022-08-30 06:27:01 +00001330 // an intermediate attribute that holds Header_libs info, and will be appended to
1331 // implementationDeps at the end, to solve the confliction that both header_libs
1332 // and static_libs use implementationDeps.
1333 var headerDeps bazel.LabelListAttribute
1334
Liz Kammer47535c52021-06-02 16:02:22 -04001335 productVarToDepFields := map[string]productVarDep{
1336 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001337 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1338 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1339 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001340 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001341 }
1342
Liz Kammer47535c52021-06-02 16:02:22 -04001343 for name, dep := range productVarToDepFields {
1344 props, exists := productVariableProps[name]
1345 excludeProps, excludesExists := productVariableProps[dep.excludesField]
Sasha Smundak39a301c2022-12-29 17:11:49 -08001346 // if neither an include nor excludes property exists, then skip it
Liz Kammer47535c52021-06-02 16:02:22 -04001347 if !exists && !excludesExists {
1348 continue
1349 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001350 // Collect all the configurations that an include or exclude property exists for.
1351 // We want to iterate all configurations rather than either the include or exclude because, for a
1352 // particular configuration, we may have either only an include or an exclude to handle.
Cole Faust150f9a52023-04-26 10:52:24 -07001353 productConfigProps := make(map[android.ProductConfigOrSoongConfigProperty]bool, len(props)+len(excludeProps))
Jingwen Chen25825ca2021-11-15 12:28:43 +00001354 for p := range props {
1355 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001356 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001357 for p := range excludeProps {
1358 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001359 }
1360
Jingwen Chen25825ca2021-11-15 12:28:43 +00001361 for productConfigProp := range productConfigProps {
1362 prop, includesExists := props[productConfigProp]
1363 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001364 var includes, excludes []string
1365 var ok bool
1366 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001367 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001368 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1369 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001370 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001371 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1372 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001373
Jingwen Chen58ff6802021-11-17 12:14:41 +00001374 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001375 dep.attribute.SetSelectValue(
1376 productConfigProp.ConfigurationAxis(),
1377 productConfigProp.SelectKey(),
1378 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1379 )
Liz Kammer47535c52021-06-02 16:02:22 -04001380 }
1381 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001382 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001383}
Liz Kammer47535c52021-06-02 16:02:22 -04001384
Liz Kammer54309532021-12-14 12:21:22 -05001385func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1386 // if system dynamic deps have the default value, any use of a system dynamic library used will
1387 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001388 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001389 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -08001390 toRemove := bazelLabelForSharedDeps(ctx, android.SortedKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001391 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001392 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1393 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001394 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001395 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1396 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001397
1398 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
1399 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, toRemove)
1400 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1401 for _, lib := range toRemove.Includes {
Spandan Das2518c022023-03-17 03:02:32 +00001402 stubLabelInApiSurfaces := bazel.Label{
1403 Label: apiSurfaceModuleLibCurrentPackage + lib.OriginalModuleName,
1404 }
1405 stubsToRemove = append(stubsToRemove, stubLabelInApiSurfaces)
Liz Kammer91487d42022-09-13 11:27:11 -04001406 }
1407 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001408 }
1409
Liz Kammere6583482021-10-19 13:56:10 -04001410 la.deps.ResolveExcludes()
1411 la.implementationDeps.ResolveExcludes()
1412 la.dynamicDeps.ResolveExcludes()
1413 la.implementationDynamicDeps.ResolveExcludes()
1414 la.wholeArchiveDeps.ResolveExcludes()
1415 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001416
Jingwen Chen91220d72021-03-24 02:18:33 -04001417}
1418
Jingwen Chened9c17d2021-04-13 07:14:55 +00001419// Relativize a list of root-relative paths with respect to the module's
1420// directory.
1421//
1422// include_dirs Soong prop are root-relative (b/183742505), but
1423// local_include_dirs, export_include_dirs and export_system_include_dirs are
1424// module dir relative. This function makes a list of paths entirely module dir
1425// relative.
1426//
1427// For the `include` attribute, Bazel wants the paths to be relative to the
1428// module.
1429func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001430 var relativePaths []string
1431 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001432 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1433 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1434 if err != nil {
1435 panic(err)
1436 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001437 relativePaths = append(relativePaths, relativePath)
1438 }
1439 return relativePaths
1440}
1441
Liz Kammer5fad5012021-09-09 14:08:21 -04001442// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1443// attributes.
1444type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001445 AbsoluteIncludes bazel.StringListAttribute
1446 Includes bazel.StringListAttribute
1447 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001448}
1449
Liz Kammer54549442022-05-11 13:55:06 -04001450func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001451 var exported BazelIncludes
1452 if includes != nil {
1453 exported = *includes
1454 } else {
1455 exported = BazelIncludes{}
1456 }
Zi Wang1cb11802022-12-09 16:08:54 -08001457
1458 // cc library Export_include_dirs and Export_system_include_dirs are marked
1459 // "variant_prepend" in struct tag, set their prepend property to true to make
1460 // sure bp2build generates correct result.
1461 exported.Includes.Prepend = true
1462 exported.SystemIncludes.Prepend = true
1463
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001464 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1465 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1466 if len(flagExporterProperties.Export_include_dirs) > 0 {
1467 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1468 }
1469 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1470 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 -04001471 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001472 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001473 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001474 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001475 exported.Includes.DeduplicateAxesFromBase()
1476 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001477
Liz Kammer5fad5012021-09-09 14:08:21 -04001478 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001479}
Chris Parsons953b3562021-09-20 15:14:39 -04001480
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001481func BazelLabelNameForStaticModule(baseLabel string) string {
1482 return baseLabel + "_bp2build_cc_library_static"
1483}
1484
Jingwen Chen55bc8202021-11-02 06:40:51 +00001485func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001486 label := android.BazelModuleLabel(ctx, m)
Sasha Smundak39a301c2022-12-29 17:11:49 -08001487 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001488 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001489 }
1490 return label
1491}
1492
Jingwen Chen55bc8202021-11-02 06:40:51 +00001493func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001494 // cc_library, at it's root name, propagates the shared library, which depends on the static
1495 // library.
1496 return android.BazelModuleLabel(ctx, m)
1497}
1498
Jingwen Chen55bc8202021-11-02 06:40:51 +00001499func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001500 label := bazelLabelForStaticModule(ctx, m)
1501 if aModule, ok := m.(android.Module); ok {
1502 if android.IsModulePrebuilt(aModule) {
1503 label += "_alwayslink"
1504 }
1505 }
1506 return label
1507}
1508
Jingwen Chen55bc8202021-11-02 06:40:51 +00001509func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001510 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1511}
1512
Jingwen Chen55bc8202021-11-02 06:40:51 +00001513func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001514 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1515}
1516
Jingwen Chen55bc8202021-11-02 06:40:51 +00001517func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001518 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1519}
1520
Jingwen Chen55bc8202021-11-02 06:40:51 +00001521func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001522 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1523}
1524
Jingwen Chen55bc8202021-11-02 06:40:51 +00001525func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001526 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1527}
1528
Jingwen Chen55bc8202021-11-02 06:40:51 +00001529func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001530 // This is not elegant, but bp2build's shared library targets only propagate
1531 // their header information as part of the normal C++ provider.
1532 return bazelLabelForSharedDeps(ctx, modules)
1533}
1534
Zi Wang0a8a1292022-08-30 06:27:01 +00001535func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1536 // This is only used when product_variable header_libs is processed, to follow
1537 // the pattern of depResolutionFunc
1538 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1539}
1540
Jingwen Chen55bc8202021-11-02 06:40:51 +00001541func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001542 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1543}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001544
1545type binaryLinkerAttrs struct {
1546 Linkshared *bool
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001547 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001548}
1549
Jingwen Chen55bc8202021-11-02 06:40:51 +00001550func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001551 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001552 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1553 linkerProps := props.(*BinaryLinkerProperties)
1554 staticExecutable := linkerProps.Static_executable
1555 if axis == bazel.NoConfigAxis {
1556 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1557 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001558 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001559 } else if staticExecutable != nil {
1560 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1561 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1562 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001563 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001564 if suffix := linkerProps.Suffix; suffix != nil {
1565 attrs.Suffix.SetSelectValue(axis, config, suffix)
1566 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001567 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001568
1569 return attrs
1570}
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001571
1572func bp2buildSanitizerFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1573 sanitizerFeatures := bazel.StringListAttribute{}
1574 bp2BuildPropParseHelper(ctx, m, &SanitizeProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1575 var features []string
1576 if sanitizerProps, ok := props.(*SanitizeProperties); ok {
1577 if sanitizerProps.Sanitize.Integer_overflow != nil && *sanitizerProps.Sanitize.Integer_overflow {
1578 features = append(features, "ubsan_integer_overflow")
1579 }
1580 for _, sanitizer := range sanitizerProps.Sanitize.Misc_undefined {
1581 features = append(features, "ubsan_"+sanitizer)
1582 }
1583 sanitizerFeatures.SetSelectValue(axis, config, features)
1584 }
1585 })
1586 return sanitizerFeatures
1587}
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +00001588
1589func bp2buildLtoFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1590 lto_feature_name := "android_thin_lto"
1591 ltoBoolFeatures := bazel.BoolAttribute{}
1592 bp2BuildPropParseHelper(ctx, m, &LTOProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1593 if ltoProps, ok := props.(*LTOProperties); ok {
1594 thinProp := ltoProps.Lto.Thin != nil && *ltoProps.Lto.Thin
1595 thinPropSetToFalse := ltoProps.Lto.Thin != nil && !*ltoProps.Lto.Thin
1596 neverProp := ltoProps.Lto.Never != nil && *ltoProps.Lto.Never
1597 if thinProp {
1598 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(true))
1599 return
1600 }
1601 if neverProp || thinPropSetToFalse {
1602 if thinProp {
1603 ctx.ModuleErrorf("lto.thin and lto.never are mutually exclusive but were specified together")
1604 } else {
1605 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(false))
1606 }
1607 return
1608 }
1609 }
1610 ltoBoolFeatures.SetSelectValue(axis, config, nil)
1611 })
1612
1613 props := m.GetArchVariantProperties(ctx, &LTOProperties{})
1614 ltoStringFeatures, err := ltoBoolFeatures.ToStringListAttribute(func(boolPtr *bool, axis bazel.ConfigurationAxis, config string) []string {
1615 if boolPtr == nil {
1616 return []string{}
1617 }
1618 if !*boolPtr {
1619 return []string{"-" + lto_feature_name}
1620 }
1621 features := []string{lto_feature_name}
1622 if ltoProps, ok := props[axis][config].(*LTOProperties); ok {
1623 if ltoProps.Whole_program_vtables != nil && *ltoProps.Whole_program_vtables {
1624 features = append(features, "android_thin_lto_whole_program_vtables")
1625 }
1626 }
1627 return features
1628 })
1629 if err != nil {
1630 ctx.ModuleErrorf("Error processing LTO attributes: %s", err)
1631 }
1632 return ltoStringFeatures
1633}
Trevor Radcliffea8b44162023-04-14 18:25:24 +00001634
1635func convertHiddenVisibilityToFeatureBase(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1636 visibilityHiddenFeature := bazel.StringListAttribute{}
1637 bp2BuildPropParseHelper(ctx, m, &BaseCompilerProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1638 if baseCompilerProps, ok := props.(*BaseCompilerProperties); ok {
1639 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, baseCompilerProps.Cflags)
1640 }
1641 })
1642 return visibilityHiddenFeature
1643}
1644
1645func convertHiddenVisibilityToFeatureStaticOrShared(ctx android.BazelConversionPathContext, m *Module, isStatic bool) bazel.StringListAttribute {
1646 visibilityHiddenFeature := bazel.StringListAttribute{}
1647 if isStatic {
1648 bp2BuildPropParseHelper(ctx, m, &StaticProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1649 if staticProps, ok := props.(*StaticProperties); ok {
1650 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, staticProps.Static.Cflags)
1651 }
1652 })
1653 } else {
1654 bp2BuildPropParseHelper(ctx, m, &SharedProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1655 if sharedProps, ok := props.(*SharedProperties); ok {
1656 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, sharedProps.Shared.Cflags)
1657 }
1658 })
1659 }
1660
1661 return visibilityHiddenFeature
1662}
1663
1664func convertHiddenVisibilityToFeatureHelper(feature *bazel.StringListAttribute, axis bazel.ConfigurationAxis, configString string, cflags []string) {
1665 if inList(config.VisibilityHiddenFlag, cflags) {
1666 feature.SetSelectValue(axis, configString, []string{"visibility_hidden"})
1667 }
1668}