blob: 96c478966abc94725b5cefd70085e4e49aaa05c9 [file] [log] [blame]
Jingwen Chen91220d72021-03-24 02:18:33 -04001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
Cole Faust7071a052022-07-29 15:58:33 -07007// http://www.apache.org/licenses/LICENSE-2.0
Jingwen Chen91220d72021-03-24 02:18:33 -04008//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14package cc
15
16import (
Liz Kammerd2871182021-10-04 13:54:37 -040017 "fmt"
Jingwen Chened9c17d2021-04-13 07:14:55 +000018 "path/filepath"
Jingwen Chen3950cd62021-05-12 04:33:00 +000019 "strings"
Chris Parsons484e50a2021-05-13 15:13:04 -040020
21 "android/soong/android"
22 "android/soong/bazel"
Alix1be00d42022-05-16 22:56:04 +000023 "android/soong/cc/config"
Liz Kammer7a210ac2021-09-22 15:52:58 -040024
Chris Parsons953b3562021-09-20 15:14:39 -040025 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040026
27 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040028)
29
Liz Kammerae3994e2021-10-19 09:45:48 -040030const (
Trevor Radcliffecee4e052022-09-06 19:31:25 +000031 cSrcPartition = "c"
32 asSrcPartition = "as"
33 asmSrcPartition = "asm"
34 lSrcPartition = "l"
35 llSrcPartition = "ll"
36 cppSrcPartition = "cpp"
37 protoSrcPartition = "proto"
38 aidlSrcPartition = "aidl"
39 syspropSrcPartition = "sysprop"
Liz Kammer91487d42022-09-13 11:27:11 -040040
41 stubsSuffix = "_stub_libs_current"
Liz Kammerae3994e2021-10-19 09:45:48 -040042)
43
Liz Kammer2222c6b2021-05-24 15:41:47 -040044// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000045// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040046type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040047 Srcs bazel.LabelListAttribute
48 Srcs_c bazel.LabelListAttribute
49 Srcs_as bazel.LabelListAttribute
50 Srcs_aidl bazel.LabelListAttribute
51 Hdrs bazel.LabelListAttribute
52 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000053
Liz Kammer12615db2021-09-28 09:19:17 -040054 Deps bazel.LabelListAttribute
55 Implementation_deps bazel.LabelListAttribute
56 Dynamic_deps bazel.LabelListAttribute
57 Implementation_dynamic_deps bazel.LabelListAttribute
58 Whole_archive_deps bazel.LabelListAttribute
59 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070060 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040061
62 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050063
64 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080065
Yu Liuf01a0f02022-12-07 15:45:30 -080066 Native_coverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -070067
Liz Kammeraceec252023-03-24 09:46:36 -040068 Apex_available []string
69
Trevor Radcliffea8b44162023-04-14 18:25:24 +000070 Features bazel.StringListAttribute
71
Yu Liufc603162022-03-01 15:44:08 -080072 sdkAttributes
Sam Delmericofb3bb322022-10-21 10:42:24 -040073
74 tidyAttributes
75}
76
77type tidyAttributes struct {
Sam Delmerico63f0c932023-03-14 14:05:28 -040078 Tidy *string
Sam Delmericofb3bb322022-10-21 10:42:24 -040079 Tidy_flags []string
80 Tidy_checks []string
81 Tidy_checks_as_errors []string
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040082 Tidy_disabled_srcs bazel.LabelListAttribute
Sam Delmerico4c902d62022-11-02 14:17:15 -040083 Tidy_timeout_srcs bazel.LabelListAttribute
Sam Delmericofb3bb322022-10-21 10:42:24 -040084}
85
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040086func (m *Module) convertTidyAttributes(ctx android.BaseMutatorContext, moduleAttrs *tidyAttributes) {
Sam Delmericofb3bb322022-10-21 10:42:24 -040087 for _, f := range m.features {
88 if tidy, ok := f.(*tidyFeature); ok {
Sam Delmerico63f0c932023-03-14 14:05:28 -040089 var tidyAttr *string
90 if tidy.Properties.Tidy != nil {
91 if *tidy.Properties.Tidy {
92 tidyAttr = proptools.StringPtr("local")
93 } else {
94 tidyAttr = proptools.StringPtr("never")
95 }
96 }
97 moduleAttrs.Tidy = tidyAttr
Sam Delmericofb3bb322022-10-21 10:42:24 -040098 moduleAttrs.Tidy_flags = tidy.Properties.Tidy_flags
99 moduleAttrs.Tidy_checks = tidy.Properties.Tidy_checks
100 moduleAttrs.Tidy_checks_as_errors = tidy.Properties.Tidy_checks_as_errors
101 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400102
103 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400104 archVariantProps := m.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
105 for axis, configToProps := range archVariantProps {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800106 for cfg, _props := range configToProps {
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400107 if archProps, ok := _props.(*BaseCompilerProperties); ok {
108 archDisabledSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_disabled_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800109 moduleAttrs.Tidy_disabled_srcs.SetSelectValue(axis, cfg, archDisabledSrcs)
Sam Delmerico4c902d62022-11-02 14:17:15 -0400110 archTimeoutSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_timeout_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800111 moduleAttrs.Tidy_timeout_srcs.SetSelectValue(axis, cfg, archTimeoutSrcs)
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400112 }
113 }
Sam Delmericofb3bb322022-10-21 10:42:24 -0400114 }
Jingwen Chen53681ef2021-04-29 08:15:13 +0000115}
116
Sam Delmericoc7681022022-02-04 21:01:20 +0000117// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000118func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400119 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
120 // macro.
121 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -0400122 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
123
124 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -0400125 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -0400126 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
127 return labelStr, false
128 }
Yu Liu2aa806b2022-09-01 11:54:47 -0700129 // If the filegroup is already converted to aidl_library or proto_library,
130 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
131 fg, _ := m.(android.FileGroupAsLibrary)
132 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -0400133 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000134 }
Liz Kammer12615db2021-09-28 09:19:17 -0400135 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400136 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000137 }
138
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400139 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +0000140 labels := bazel.LabelPartitions{
141 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500142 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
143 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -0700144 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -0400145 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000146 // TODO(http://b/231968910): If there is ever a filegroup target that
147 // contains .l or .ll files we will need to find a way to add a
148 // LabelMapper for these that identifies these filegroups and
149 // converts them appropriately
150 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
151 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400152 // C++ is the "catch-all" group, and comprises generated sources because we don't
153 // know the language of these sources until the genrule is executed.
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000154 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
155 syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
Sam Delmericoc7681022022-02-04 21:01:20 +0000156 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000157
Sam Delmericoc7681022022-02-04 21:01:20 +0000158 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000159}
160
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000161// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000162func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000163 lib, ok := module.compiler.(*libraryDecorator)
164 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400165 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000166 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000167 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
168}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000169
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000170// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000171func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000172 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000173}
174
175// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000176func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000177 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400178}
179
Liz Kammer7a210ac2021-09-22 15:52:58 -0400180type depsPartition struct {
181 export bazel.LabelList
182 implementation bazel.LabelList
183}
184
Jingwen Chen55bc8202021-11-02 06:40:51 +0000185type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400186
Jingwen Chen55bc8202021-11-02 06:40:51 +0000187func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400188 if !exportsDeps {
189 return depsPartition{
190 implementation: fn(ctx, allDeps),
191 }
192 }
193
Liz Kammer7a210ac2021-09-22 15:52:58 -0400194 implementation, export := android.FilterList(allDeps, exportedDeps)
195
196 return depsPartition{
197 export: fn(ctx, export),
198 implementation: fn(ctx, implementation),
199 }
200}
201
Jingwen Chen55bc8202021-11-02 06:40:51 +0000202type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400203
Jingwen Chen55bc8202021-11-02 06:40:51 +0000204func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400205 if !exportsDeps {
206 return depsPartition{
207 implementation: fn(ctx, allDeps, excludes),
208 }
209 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400210 implementation, export := android.FilterList(allDeps, exportedDeps)
211
212 return depsPartition{
213 export: fn(ctx, export, excludes),
214 implementation: fn(ctx, implementation, excludes),
215 }
216}
217
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000218func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
219 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800220 for cfg, props := range configToProps {
221 parseFunc(axis, cfg, props)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000222 }
223 }
224}
225
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000226// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Liz Kammeraceec252023-03-24 09:46:36 -0400227func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400228 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000229
Liz Kammer9abd62d2021-05-21 08:37:59 -0400230 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000231 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutHiddenVisibility))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000232 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400233 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400234
Liz Kammer2b8004b2021-10-04 13:55:44 -0400235 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400236 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
237 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
238
Liz Kammer2b8004b2021-10-04 13:55:44 -0400239 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400240 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
241 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
242
243 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500244 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000245 }
Liz Kammer135bf552021-08-11 10:46:06 -0400246 // system_dynamic_deps distinguishes between nil/empty list behavior:
247 // nil -> use default values
248 // empty list -> no values specified
249 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000250
Liz Kammeraceec252023-03-24 09:46:36 -0400251 var apexAvailable []string
Jingwen Chenbcf53042021-05-26 04:42:42 +0000252 if isStatic {
Liz Kammeraceec252023-03-24 09:46:36 -0400253 apexAvailable = lib.StaticProperties.Static.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000254 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
255 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
256 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000257 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000258 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000259 } else {
Liz Kammeraceec252023-03-24 09:46:36 -0400260 apexAvailable = lib.SharedProperties.Shared.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000261 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
262 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
263 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000264 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000265 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000266 }
267
Liz Kammerae3994e2021-10-19 09:45:48 -0400268 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
269 attrs.Srcs = partitionedSrcs[cppSrcPartition]
270 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
271 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000272
Liz Kammeraceec252023-03-24 09:46:36 -0400273 attrs.Apex_available = android.ConvertApexAvailableToTags(apexAvailable)
274
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000275 attrs.Features.Append(convertHiddenVisibilityToFeatureStaticOrShared(ctx, module, isStatic))
276
Liz Kammer12615db2021-09-28 09:19:17 -0400277 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
278 // TODO(b/208815215): determine whether this is used and add support if necessary
279 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
280 }
281
Jingwen Chenbcf53042021-05-26 04:42:42 +0000282 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000283}
284
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400285// Convenience struct to hold all attributes parsed from prebuilt properties.
286type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000287 Src bazel.LabelAttribute
288 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400289}
290
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000291func parseSrc(ctx android.BazelConversionPathContext, srcLabelAttribute *bazel.LabelAttribute, axis bazel.ConfigurationAxis, config string, srcs []string) {
292 srcFileError := func() {
293 ctx.ModuleErrorf("parseSrc: Expected at most one source file for %s %s\n", axis, config)
294 }
295 if len(srcs) > 1 {
296 srcFileError()
297 return
298 } else if len(srcs) == 0 {
299 return
300 }
301 if srcLabelAttribute.SelectValue(axis, config) != nil {
302 srcFileError()
303 return
304 }
305 srcLabelAttribute.SetSelectValue(axis, config, android.BazelLabelForModuleSrcSingle(ctx, srcs[0]))
306}
307
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000308// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000309func 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 +0000310
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400311 var srcLabelAttribute bazel.LabelAttribute
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000312 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
313 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000314 parseSrc(ctx, &srcLabelAttribute, axis, config, prebuiltLinkerProperties.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000315 }
316 })
317
318 var enabledLabelAttribute bazel.BoolAttribute
319 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
320 if props.Enabled != nil {
321 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
322 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000323 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000324 }
325
326 if isStatic {
327 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
328 if staticProperties, ok := props.(*StaticProperties); ok {
329 parseAttrs(axis, config, staticProperties.Static)
330 }
331 })
332 } else {
333 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
334 if sharedProperties, ok := props.(*SharedProperties); ok {
335 parseAttrs(axis, config, sharedProperties.Shared)
336 }
337 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400338 }
339
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400340 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000341 Src: srcLabelAttribute,
342 Enabled: enabledLabelAttribute,
343 }
344}
345
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000346func bp2BuildParsePrebuiltBinaryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
347 var srcLabelAttribute bazel.LabelAttribute
348 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
349 if props, ok := props.(*prebuiltLinkerProperties); ok {
350 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000351 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000352 })
353
354 return prebuiltAttributes{
355 Src: srcLabelAttribute,
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400356 }
357}
358
Colin Crossc5075e92022-12-05 16:46:39 -0800359func bp2BuildParsePrebuiltObjectProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
360 var srcLabelAttribute bazel.LabelAttribute
361 bp2BuildPropParseHelper(ctx, module, &prebuiltObjectProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
362 if props, ok := props.(*prebuiltObjectProperties); ok {
363 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
364 }
365 })
366
367 return prebuiltAttributes{
368 Src: srcLabelAttribute,
369 }
370}
371
Liz Kammere6583482021-10-19 13:56:10 -0400372type baseAttributes struct {
373 compilerAttributes
374 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400375
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000376 // A combination of compilerAttributes.features and linkerAttributes.features, as well as sanitizer features
Cole Faust5fa4e962022-08-22 14:31:04 -0700377 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400378 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400379 aidlDependency *bazel.LabelAttribute
Yu Liuf01a0f02022-12-07 15:45:30 -0800380 Native_coverage *bool
Liz Kammere6583482021-10-19 13:56:10 -0400381}
382
Jingwen Chen107c0de2021-04-09 10:43:12 +0000383// Convenience struct to hold all attributes parsed from compiler properties.
384type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400385 // Options for all languages
386 copts bazel.StringListAttribute
387 // Assembly options and sources
388 asFlags bazel.StringListAttribute
389 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700390 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400391 // C options and sources
392 conlyFlags bazel.StringListAttribute
393 cSrcs bazel.LabelListAttribute
394 // C++ options and sources
395 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000396 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400397
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000398 // Lex sources and options
399 lSrcs bazel.LabelListAttribute
400 llSrcs bazel.LabelListAttribute
401 lexopts bazel.StringListAttribute
402
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000403 // Sysprop sources
404 syspropSrcs bazel.LabelListAttribute
405
Liz Kammere6583482021-10-19 13:56:10 -0400406 hdrs bazel.LabelListAttribute
407
Chris Parsons2c788392021-08-10 11:58:07 -0400408 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000409
410 // Not affected by arch variants
411 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500412 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000413 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400414
415 localIncludes bazel.StringListAttribute
416 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400417
Liz Kammer1263d9b2021-12-10 14:28:20 -0500418 includes BazelIncludes
419
Liz Kammer12615db2021-09-28 09:19:17 -0400420 protoSrcs bazel.LabelListAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400421 aidlSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000422
423 stubsSymbolFile *string
424 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700425
426 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500427
428 suffix bazel.StringAttribute
Vinh Tran99270ea2022-11-28 11:15:23 -0500429
430 fdoProfile bazel.LabelAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000431}
432
Liz Kammercac7f692021-12-16 14:19:32 -0500433type filterOutFn func(string) bool
434
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000435// filterOutHiddenVisibility removes the flag specifying hidden visibility as
436// this flag is converted to a toolchain feature
437func filterOutHiddenVisibility(flag string) bool {
438 return flag == config.VisibilityHiddenFlag
439}
440
Liz Kammercac7f692021-12-16 14:19:32 -0500441func filterOutStdFlag(flag string) bool {
442 return strings.HasPrefix(flag, "-std=")
443}
444
Alix1be00d42022-05-16 22:56:04 +0000445func filterOutClangUnknownCflags(flag string) bool {
446 for _, f := range config.ClangUnknownCflags {
447 if f == flag {
448 return true
449 }
450 }
451 return false
452}
453
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000454func parseCommandLineFlags(soongFlags []string, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400455 var result []string
456 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000457 skipFlag := false
458 for _, filter := range filterOut {
459 if filter != nil && filter(flag) {
460 skipFlag = true
461 }
462 }
463 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500464 continue
465 }
Liz Kammere6583482021-10-19 13:56:10 -0400466 // Soong's cflags can contain spaces, like `-include header.h`. For
467 // Bazel's copts, split them up to be compatible with the
468 // no_copts_tokenization feature.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000469 result = append(result, strings.Split(flag, " ")...)
Liz Kammere6583482021-10-19 13:56:10 -0400470 }
471 return result
472}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000473
Jingwen Chen55bc8202021-11-02 06:40:51 +0000474func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400475 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
476 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
477 if srcsList, ok := parseSrcs(ctx, props); ok {
478 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400479 }
480
Liz Kammere6583482021-10-19 13:56:10 -0400481 localIncludeDirs := props.Local_include_dirs
482 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500483 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400484 if includeBuildDirectory(props.Include_build_directory) {
485 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400486 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000487 }
488
Liz Kammere6583482021-10-19 13:56:10 -0400489 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
490 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
491
Cole Faust5fa4e962022-08-22 14:31:04 -0700492 instructionSet := proptools.StringDefault(props.Instruction_set, "")
493 if instructionSet == "arm" {
494 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm", "-arm_isa_thumb"})
495 } else if instructionSet != "" && instructionSet != "thumb" {
496 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
497 }
498
Liz Kammercac7f692021-12-16 14:19:32 -0500499 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
500 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
501 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
502 // cases.
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000503 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutClangUnknownCflags, filterOutHiddenVisibility))
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000504 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
505 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, filterOutClangUnknownCflags))
506 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400507 ca.rtti.SetSelectValue(axis, config, props.Rtti)
508}
509
Jingwen Chen55bc8202021-11-02 06:40:51 +0000510func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000511 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
512 if stlProps, ok := props.(*StlProperties); ok {
513 if stlProps.Stl == nil {
514 return
515 }
516 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400517 stl := deduplicateStlInput(*stlProps.Stl)
518 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000519 } else if ca.stl != stlProps.Stl {
520 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 -0400521 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000522 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000523 })
Liz Kammere6583482021-10-19 13:56:10 -0400524}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000525
Jingwen Chen55bc8202021-11-02 06:40:51 +0000526func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400527 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400528 "Cflags": &ca.copts,
529 "Asflags": &ca.asFlags,
530 "CppFlags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400531 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400532 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000533 if productConfigProps, exists := productVariableProps[propName]; exists {
534 for productConfigProp, prop := range productConfigProps {
535 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400536 if !ok {
537 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
538 }
Jingwen Chen25825ca2021-11-15 12:28:43 +0000539 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name)
540 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400541 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400542 }
543 }
Liz Kammere6583482021-10-19 13:56:10 -0400544}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400545
Jingwen Chen55bc8202021-11-02 06:40:51 +0000546func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400547 ca.srcs.ResolveExcludes()
548 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
549
Liz Kammer12615db2021-09-28 09:19:17 -0400550 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400551 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400552
Liz Kammere6583482021-10-19 13:56:10 -0400553 for p, lla := range partitionedSrcs {
554 // if there are no sources, there is no need for headers
555 if lla.IsEmpty() {
556 continue
557 }
558 lla.Append(implementationHdrs)
559 partitionedSrcs[p] = lla
560 }
561
562 ca.srcs = partitionedSrcs[cppSrcPartition]
563 ca.cSrcs = partitionedSrcs[cSrcPartition]
564 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700565 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000566 ca.lSrcs = partitionedSrcs[lSrcPartition]
567 ca.llSrcs = partitionedSrcs[llSrcPartition]
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000568 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400569
570 ca.absoluteIncludes.DeduplicateAxesFromBase()
571 ca.localIncludes.DeduplicateAxesFromBase()
572}
573
574// Parse srcs from an arch or OS's props value.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000575func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400576 anySrcs := false
577 // Add srcs-like dependencies such as generated files.
578 // First create a LabelList containing these dependencies, then merge the values with srcs.
579 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, props.Generated_sources, props.Exclude_generated_sources)
580 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
581 anySrcs = true
582 }
583
584 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400585
Liz Kammere6583482021-10-19 13:56:10 -0400586 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
587 anySrcs = true
588 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400589
Liz Kammere6583482021-10-19 13:56:10 -0400590 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
591}
592
Liz Kammera5a29de2022-05-25 23:19:37 -0400593func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
594 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500595 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
596 // Defaults are handled by the toolchain definition.
597 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400598 stdVal := proptools.StringDefault(std, defaultVal)
599 if stdVal == "experimental" || stdVal == defaultVal {
600 if stdVal == "experimental" {
601 stdVal = prefix + "_std_experimental"
602 }
603 if !useGnu {
604 stdVal += "_no_gnu"
605 }
606 } else if !useGnu {
607 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500608 }
609
Liz Kammera5a29de2022-05-25 23:19:37 -0400610 if stdVal == defaultVal {
611 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500612 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400613 return &stdVal
614}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500615
Liz Kammera5a29de2022-05-25 23:19:37 -0400616func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
617 useGnu := useGnuExtensions(gnu_extensions)
618
619 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400620}
621
Liz Kammer1263d9b2021-12-10 14:28:20 -0500622// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
623// is fully-qualified.
624// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
625func packageFromLabel(label string) (string, bool) {
626 split := strings.Split(label, ":")
627 if len(split) != 2 {
628 return "", false
629 }
630 if split[0] == "" {
631 return ".", false
632 }
633 // remove leading "//"
634 return split[0][2:], true
635}
636
637// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
638func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
639 for _, hdr := range labelList.Includes {
640 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
641 absolute = append(absolute, pkg)
642 } else if pkg != "" {
643 relative = append(relative, pkg)
644 }
645 }
646 return relative, absolute
647}
648
Cole Faust7071a052022-07-29 15:58:33 -0700649type YasmAttributes struct {
650 Srcs bazel.LabelListAttribute
651 Flags bazel.StringListAttribute
652 Include_dirs bazel.StringListAttribute
653}
654
655func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
656 if ca.asmSrcs.IsEmpty() {
657 return nil
658 }
659
660 // Yasm needs the include directories from both local_includes and
661 // export_include_dirs. We don't care about actually exporting them from the
662 // yasm rule though, because they will also be present on the cc_ rule that
663 // wraps this yasm rule.
664 includes := ca.localIncludes.Clone()
665 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
666 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
667 if len(flagExporterProperties.Export_include_dirs) > 0 {
668 x := bazel.StringListAttribute{}
669 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
670 includes.Append(x)
671 }
672 }
673 })
674
675 ctx.CreateBazelTargetModule(
676 bazel.BazelTargetModuleProperties{
677 Rule_class: "yasm",
678 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
679 },
680 android.CommonAttributes{Name: m.Name() + "_yasm"},
681 &YasmAttributes{
682 Srcs: ca.asmSrcs,
683 Flags: ca.asFlags,
684 Include_dirs: *includes,
685 })
686
687 // We only want to add a dependency on the _yasm target if there are asm
688 // sources in the current configuration. If there are unconfigured asm
689 // sources, always add the dependency. Otherwise, add the dependency only
690 // on the configuration axes and values that had asm sources.
691 if len(ca.asmSrcs.Value.Includes) > 0 {
692 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
693 }
694
695 ret := &bazel.LabelAttribute{}
696 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800697 for cfg := range ca.asmSrcs.ConfigurableValues[axis] {
698 ret.SetSelectValue(axis, cfg, bazel.Label{Label: ":" + m.Name() + "_yasm"})
Cole Faust7071a052022-07-29 15:58:33 -0700699 }
700 }
701 return ret
702}
703
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000704// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400705func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400706 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
707 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000708 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400709
710 var implementationHdrs bazel.LabelListAttribute
711
712 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
713 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
714 for axis, configMap := range cp {
715 if _, ok := axisToConfigs[axis]; !ok {
716 axisToConfigs[axis] = map[string]bool{}
717 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800718 for cfg := range configMap {
719 axisToConfigs[axis][cfg] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400720 }
721 }
722 }
Liz Kammere6583482021-10-19 13:56:10 -0400723 allAxesAndConfigs(archVariantCompilerProps)
724 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000725 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400726
Liz Kammere6583482021-10-19 13:56:10 -0400727 compilerAttrs := compilerAttributes{}
728 linkerAttrs := linkerAttributes{}
729
Chris Parsons7b3289b2023-01-26 17:30:44 -0500730 // Iterate through these axes in a deterministic order. This is required
731 // because processing certain dependencies may result in concatenating
732 // elements along other axes. (For example, processing NoConfig may result
733 // in elements being added to InApex). This is thus the only way to ensure
734 // that the order of entries in each list is in a predictable order.
735 for _, axis := range bazel.SortedConfigurationAxes(axisToConfigs) {
736 configs := axisToConfigs[axis]
Sasha Smundak39a301c2022-12-29 17:11:49 -0800737 for cfg := range configs {
Liz Kammere6583482021-10-19 13:56:10 -0400738 var allHdrs []string
Sasha Smundak39a301c2022-12-29 17:11:49 -0800739 if baseCompilerProps, ok := archVariantCompilerProps[axis][cfg].(*BaseCompilerProperties); ok {
Liz Kammere6583482021-10-19 13:56:10 -0400740 allHdrs = baseCompilerProps.Generated_headers
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000741 if baseCompilerProps.Lex != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800742 compilerAttrs.lexopts.SetSelectValue(axis, cfg, baseCompilerProps.Lex.Flags)
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000743 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800744 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, cfg, baseCompilerProps)
Liz Kammere6583482021-10-19 13:56:10 -0400745 }
746
747 var exportHdrs []string
748
Sasha Smundak39a301c2022-12-29 17:11:49 -0800749 if baseLinkerProps, ok := archVariantLinkerProps[axis][cfg].(*BaseLinkerProperties); ok {
Liz Kammere6583482021-10-19 13:56:10 -0400750 exportHdrs = baseLinkerProps.Export_generated_headers
751
Liz Kammer48cdbeb2023-03-17 10:17:50 -0400752 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module, axis, cfg, baseLinkerProps)
Liz Kammere6583482021-10-19 13:56:10 -0400753 }
754 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800755 implementationHdrs.SetSelectValue(axis, cfg, headers.implementation)
756 compilerAttrs.hdrs.SetSelectValue(axis, cfg, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500757
758 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800759 compilerAttrs.includes.Includes.SetSelectValue(axis, cfg, exportIncludes)
760 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, cfg, exportAbsoluteIncludes)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500761
762 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800763 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, cfg)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500764 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400765
Sasha Smundak39a301c2022-12-29 17:11:49 -0800766 compilerAttrs.absoluteIncludes.SetSelectValue(axis, cfg, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400767
Sasha Smundak39a301c2022-12-29 17:11:49 -0800768 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, cfg)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500769 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400770
Sasha Smundak39a301c2022-12-29 17:11:49 -0800771 compilerAttrs.localIncludes.SetSelectValue(axis, cfg, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000772
Sasha Smundak39a301c2022-12-29 17:11:49 -0800773 if libraryProps, ok := archVariantLibraryProperties[axis][cfg].(*LibraryProperties); ok {
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000774 if axis == bazel.NoConfigAxis {
775 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
Usta (Tsering) Shrestha1db43482023-04-19 14:02:52 +0000776 compilerAttrs.stubsVersions.SetSelectValue(axis, cfg, libraryProps.Stubs.Versions)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000777 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500778 if suffix := libraryProps.Suffix; suffix != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800779 compilerAttrs.suffix.SetSelectValue(axis, cfg, suffix)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500780 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000781 }
Liz Kammere6583482021-10-19 13:56:10 -0400782 }
783 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400784
Liz Kammere6583482021-10-19 13:56:10 -0400785 compilerAttrs.convertStlProps(ctx, module)
786 (&linkerAttrs).convertStripProps(ctx, module)
787
Yu Liuf01a0f02022-12-07 15:45:30 -0800788 var nativeCoverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -0700789 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
790 !Bool(module.coverage.Properties.Native_coverage) {
Yu Liuf01a0f02022-12-07 15:45:30 -0800791 nativeCoverage = BoolPtr(false)
Yu Liu8d82ac52022-05-17 15:13:28 -0700792 }
793
Cole Faust912bc882023-03-08 12:29:50 -0800794 productVariableProps := android.ProductVariableProperties(ctx, ctx.Module())
Liz Kammere6583482021-10-19 13:56:10 -0400795
796 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
797 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
798
799 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500800 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400801
Cole Faust7071a052022-07-29 15:58:33 -0700802 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
803
Liz Kammer12615db2021-09-28 09:19:17 -0400804 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
805
806 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
807 // which. This will add the newly generated proto library to the appropriate attribute and nothing
808 // to the other
809 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
810 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400811
Vinh Tran395a1e92022-09-16 18:27:29 -0400812 aidlDep := bp2buildCcAidlLibrary(ctx, module, compilerAttrs.aidlSrcs, linkerAttrs)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400813 if aidlDep != nil {
814 if lib, ok := module.linker.(*libraryDecorator); ok {
815 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
816 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
817 } else {
818 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
819 }
820 }
821 }
Liz Kammer12615db2021-09-28 09:19:17 -0400822
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000823 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
824 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
825 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
826
Vinh Tran99270ea2022-11-28 11:15:23 -0500827 if module.afdo != nil && module.afdo.Properties.Afdo {
828 fdoProfileDep := bp2buildFdoProfile(ctx, module)
829 if fdoProfileDep != nil {
830 (&compilerAttrs).fdoProfile.SetValue(*fdoProfileDep)
831 }
832 }
833
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000834 if !compilerAttrs.syspropSrcs.IsEmpty() {
835 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
836 }
837
Zi Wang9f609db2023-01-04 11:06:54 -0800838 linkerAttrs.wholeArchiveDeps.Prepend = true
839 linkerAttrs.deps.Prepend = true
840 compilerAttrs.localIncludes.Prepend = true
841 compilerAttrs.absoluteIncludes.Prepend = true
842 compilerAttrs.hdrs.Prepend = true
843
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000844 features := compilerAttrs.features.Clone().Append(linkerAttrs.features).Append(bp2buildSanitizerFeatures(ctx, module))
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +0000845 features = features.Append(bp2buildLtoFeatures(ctx, module))
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000846 features = features.Append(convertHiddenVisibilityToFeatureBase(ctx, module))
Cole Faust5fa4e962022-08-22 14:31:04 -0700847 features.DeduplicateAxesFromBase()
848
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +0000849 addMuslSystemDynamicDeps(ctx, linkerAttrs)
850
Liz Kammere6583482021-10-19 13:56:10 -0400851 return baseAttributes{
852 compilerAttrs,
853 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700854 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400855 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400856 aidlDep,
Yu Liuf01a0f02022-12-07 15:45:30 -0800857 nativeCoverage,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000858 }
859}
860
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +0000861// As a workaround for b/261657184, we are manually adding the default value
862// of system_dynamic_deps for the linux_musl os.
863// TODO: Solve this properly
864func addMuslSystemDynamicDeps(ctx android.Bp2buildMutatorContext, attrs linkerAttributes) {
865 systemDynamicDeps := attrs.systemDynamicDeps.SelectValue(bazel.OsConfigurationAxis, "linux_musl")
866 if attrs.systemDynamicDeps.HasAxisSpecificValues(bazel.OsConfigurationAxis) && systemDynamicDeps.IsNil() {
867 attrs.systemDynamicDeps.SetSelectValue(bazel.OsConfigurationAxis, "linux_musl", android.BazelLabelForModuleDeps(ctx, config.MuslDefaultSharedLibraries))
868 }
869}
870
Vinh Tran99270ea2022-11-28 11:15:23 -0500871type fdoProfileAttributes struct {
872 Absolute_path_profile string
873}
874
875func bp2buildFdoProfile(
876 ctx android.Bp2buildMutatorContext,
877 m *Module,
878) *bazel.Label {
879 for _, project := range globalAfdoProfileProjects {
Vinh Tranbc9c8b42022-12-09 12:03:52 -0500880 // Ensure handcrafted BUILD file exists in the project
881 BUILDPath := android.ExistentPathForSource(ctx, project, "BUILD")
882 if BUILDPath.Valid() {
883 // We handcraft a BUILD file with fdo_profile targets that use the existing profiles in the project
884 // This implementation is assuming that every afdo profile in globalAfdoProfileProjects already has
885 // an associated fdo_profile target declared in the same package.
886 // TODO(b/260714900): Handle arch-specific afdo profiles (e.g. `<module-name>-arm<64>.afdo`)
887 path := android.ExistentPathForSource(ctx, project, m.Name()+".afdo")
888 if path.Valid() {
889 // FIXME: Some profiles only exist internally and are not released to AOSP.
890 // When generated BUILD files are checked in, we'll run into merge conflict.
891 // The cc_library_shared target in AOSP won't have reference to an fdo_profile target because
892 // the profile doesn't exist. Internally, the same cc_library_shared target will
893 // have reference to the fdo_profile.
894 // For more context, see b/258682955#comment2
895 fdoProfileLabel := "//" + strings.TrimSuffix(project, "/") + ":" + m.Name()
896 return &bazel.Label{
897 Label: fdoProfileLabel,
898 }
Vinh Tran99270ea2022-11-28 11:15:23 -0500899 }
900 }
901 }
902
903 return nil
904}
905
Vinh Tran9f6796a2022-08-16 13:10:31 -0400906func bp2buildCcAidlLibrary(
907 ctx android.Bp2buildMutatorContext,
908 m *Module,
Vinh Trana3b8b782022-09-14 11:40:24 -0400909 aidlLabelList bazel.LabelListAttribute,
Vinh Tran395a1e92022-09-16 18:27:29 -0400910 linkerAttrs linkerAttributes,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400911) *bazel.LabelAttribute {
Vinh Trana3b8b782022-09-14 11:40:24 -0400912 if !aidlLabelList.IsEmpty() {
913 aidlLibs, aidlSrcs := aidlLabelList.Partition(func(src bazel.Label) bool {
914 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
915 fg.ShouldConvertToAidlLibrary(ctx) {
916 return true
917 }
918 return false
919 })
Vinh Tran9f6796a2022-08-16 13:10:31 -0400920
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400921 apexAvailableTags := android.ApexAvailableTags(ctx.Module())
922 sdkAttrs := bp2BuildParseSdkAttributes(m)
923
Vinh Trana3b8b782022-09-14 11:40:24 -0400924 if !aidlSrcs.IsEmpty() {
925 aidlLibName := m.Name() + "_aidl_library"
926 ctx.CreateBazelTargetModule(
927 bazel.BazelTargetModuleProperties{
928 Rule_class: "aidl_library",
Sam Delmericoe55bf082023-03-31 09:47:28 -0400929 Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
Vinh Trana3b8b782022-09-14 11:40:24 -0400930 },
931 android.CommonAttributes{Name: aidlLibName},
932 &aidlLibraryAttributes{
933 Srcs: aidlSrcs,
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400934 Tags: apexAvailableTags,
Vinh Trana3b8b782022-09-14 11:40:24 -0400935 },
936 )
937 aidlLibs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
938 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400939
Vinh Trana3b8b782022-09-14 11:40:24 -0400940 if !aidlLibs.IsEmpty() {
941 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
Sam Delmerico512437b2023-03-17 11:34:15 -0400942 // Since parent cc_library already has these dependencies, we can add them as implementation
943 // deps so that they don't re-export
944 implementationDeps := linkerAttrs.deps.Clone()
945 implementationDeps.Append(linkerAttrs.implementationDeps)
946 implementationDynamicDeps := linkerAttrs.dynamicDeps.Clone()
947 implementationDynamicDeps.Append(linkerAttrs.implementationDynamicDeps)
Vinh Tran395a1e92022-09-16 18:27:29 -0400948
Vinh Trana3b8b782022-09-14 11:40:24 -0400949 ctx.CreateBazelTargetModule(
950 bazel.BazelTargetModuleProperties{
951 Rule_class: "cc_aidl_library",
952 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
953 },
954 android.CommonAttributes{Name: ccAidlLibrarylabel},
955 &ccAidlLibraryAttributes{
Vinh Tran395a1e92022-09-16 18:27:29 -0400956 Deps: aidlLibs,
Sam Delmerico512437b2023-03-17 11:34:15 -0400957 Implementation_deps: *implementationDeps,
958 Implementation_dynamic_deps: *implementationDynamicDeps,
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400959 Tags: apexAvailableTags,
960 sdkAttributes: sdkAttrs,
Vinh Trana3b8b782022-09-14 11:40:24 -0400961 },
962 )
963 label := &bazel.LabelAttribute{
964 Value: &bazel.Label{
965 Label: ":" + ccAidlLibrarylabel,
966 },
967 }
968 return label
969 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400970 }
971
Vinh Trana3b8b782022-09-14 11:40:24 -0400972 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -0400973}
974
Yu Liufc603162022-03-01 15:44:08 -0800975func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000976 return sdkAttributes{
977 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -0800978 Min_sdk_version: module.Properties.Min_sdk_version,
979 }
980}
981
982type sdkAttributes struct {
983 Sdk_version *string
984 Min_sdk_version *string
985}
986
Jingwen Chen107c0de2021-04-09 10:43:12 +0000987// Convenience struct to hold all attributes parsed from linker properties.
988type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -0500989 deps bazel.LabelListAttribute
990 implementationDeps bazel.LabelListAttribute
991 dynamicDeps bazel.LabelListAttribute
992 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -0700993 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -0500994 wholeArchiveDeps bazel.LabelListAttribute
995 implementationWholeArchiveDeps bazel.LabelListAttribute
996 systemDynamicDeps bazel.LabelListAttribute
997 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -0400998
Rupert Shuttleworth484aa252021-12-10 07:22:53 -0500999 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001000 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -04001001 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001002 stripKeepSymbols bazel.BoolAttribute
1003 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
1004 stripKeepSymbolsList bazel.StringListAttribute
1005 stripAll bazel.BoolAttribute
1006 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -04001007 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -04001008}
1009
Liz Kammer54309532021-12-14 12:21:22 -05001010var (
1011 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -04001012 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -05001013)
1014
Vinh Tran85fb07c2022-09-16 16:17:48 -04001015// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
1016// since all libs are already excluded by default
Liz Kammer748d7072023-01-25 12:07:43 -05001017func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, props *BaseLinkerProperties) {
1018 excludeSharedLibs := bazelLabelForSharedDeps(ctx, props.Target.Apex.Exclude_shared_libs)
1019 sharedExcludes := bazel.LabelList{Excludes: excludeSharedLibs.Includes}
1020 sharedExcludesLabelList := bazel.LabelListAttribute{}
1021 sharedExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, sharedExcludes)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001022
Liz Kammer748d7072023-01-25 12:07:43 -05001023 la.dynamicDeps.Append(sharedExcludesLabelList)
1024 la.implementationDynamicDeps.Append(sharedExcludesLabelList)
1025
1026 excludeStaticLibs := bazelLabelForStaticDeps(ctx, props.Target.Apex.Exclude_static_libs)
1027 staticExcludes := bazel.LabelList{Excludes: excludeStaticLibs.Includes}
1028 staticExcludesLabelList := bazel.LabelListAttribute{}
1029 staticExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, staticExcludes)
1030
1031 la.deps.Append(staticExcludesLabelList)
1032 la.implementationDeps.Append(staticExcludesLabelList)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001033}
1034
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001035func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, module *Module, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
1036 isBinary := module.Binary()
Liz Kammere6583482021-10-19 13:56:10 -04001037 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
1038 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -04001039
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001040 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -04001041 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
1042 if axis == bazel.NoConfigAxis {
1043 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
1044 if proptools.Bool(props.Use_version_lib) {
1045 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
1046 // remove from static libs so there is no duplicate dependency
1047 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
1048 // only add the dep if it is not in progress
1049 if !versionLibAlreadyInDeps {
1050 if isBinary {
1051 wholeStaticLibs = append(wholeStaticLibs, versionLib)
1052 } else {
1053 la.implementationWholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, []string{versionLib}, props.Exclude_static_libs))
1054 }
1055 }
1056 }
1057 }
1058
Liz Kammere6583482021-10-19 13:56:10 -04001059 // Excludes to parallel Soong:
1060 // 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 -04001061 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001062
Vinh Tran85fb07c2022-09-16 16:17:48 -04001063 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1064 ctx,
1065 !isBinary,
1066 staticLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001067 props.Exclude_static_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001068 props.Export_static_lib_headers,
1069 bazelLabelForStaticDepsExcludes,
1070 )
Liz Kammer7a210ac2021-09-22 15:52:58 -04001071
Liz Kammere6583482021-10-19 13:56:10 -04001072 headerLibs := android.FirstUniqueStrings(props.Header_libs)
1073 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -04001074
Liz Kammere6583482021-10-19 13:56:10 -04001075 (&hDeps.export).Append(staticDeps.export)
1076 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001077
Liz Kammere6583482021-10-19 13:56:10 -04001078 (&hDeps.implementation).Append(staticDeps.implementation)
1079 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -04001080
Liz Kammere6583482021-10-19 13:56:10 -04001081 systemSharedLibs := props.System_shared_libs
1082 // systemSharedLibs distinguishes between nil/empty list behavior:
1083 // nil -> use default values
1084 // empty list -> no values specified
1085 if len(systemSharedLibs) > 0 {
1086 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
1087 }
1088 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
1089
1090 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -05001091 excludeSharedLibs := props.Exclude_shared_libs
1092 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
1093 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
1094 })
1095 for _, el := range usedSystem {
1096 if la.usedSystemDynamicDepAsDynamicDep == nil {
1097 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
1098 }
1099 la.usedSystemDynamicDepAsDynamicDep[el] = true
1100 }
1101
Vinh Tran85fb07c2022-09-16 16:17:48 -04001102 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1103 ctx,
1104 !isBinary,
1105 sharedLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001106 props.Exclude_shared_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001107 props.Export_shared_lib_headers,
1108 bazelLabelForSharedDepsExcludes,
1109 )
Liz Kammere6583482021-10-19 13:56:10 -04001110 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
1111 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Liz Kammer748d7072023-01-25 12:07:43 -05001112 la.resolveTargetApexProp(ctx, props)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001113
Wei Li81852ca2022-07-27 00:22:06 -07001114 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
Yu Liu10174ff2023-02-21 12:05:26 -08001115 // If a dependency in la.implementationDynamicDeps or la.dynamicDeps has stubs, its
1116 // stub variant should be used when the dependency is linked in a APEX. The
1117 // dependencies in NoConfigAxis and OsConfigurationAxis/OsAndroid are grouped by
1118 // having stubs or not, so Bazel select() statement can be used to choose
1119 // source/stub variants of them.
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001120 apexAvailable := module.ApexAvailable()
1121 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.export, &la.dynamicDeps, 0)
1122 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.implementation, &la.implementationDynamicDeps, 1)
Wei Li81852ca2022-07-27 00:22:06 -07001123 }
Liz Kammere6583482021-10-19 13:56:10 -04001124
1125 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1126 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1127 }
1128
1129 if Bool(props.Allow_undefined_symbols) {
1130 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1131 }
1132
1133 var linkerFlags []string
1134 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001135 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001136 // binaries remove static flag if -shared is in the linker flags
1137 if isBinary && android.InList("-shared", linkerFlags) {
1138 axisFeatures = append(axisFeatures, "-static_flag")
1139 }
1140 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001141
Alex Márquez Pérez Muñíz Díaz Puras Thaureaux01ec55e2023-01-30 22:53:04 +00001142 if !props.libCrt() {
1143 axisFeatures = append(axisFeatures, "-use_libcrt")
1144 }
1145 if !props.crt() {
1146 axisFeatures = append(axisFeatures, "-link_crt")
1147 }
1148
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001149 // This must happen before the addition of flags for Version Script and
1150 // Dynamic List, as these flags must be split on spaces and those must not
1151 linkerFlags = parseCommandLineFlags(linkerFlags, filterOutClangUnknownCflags)
1152
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001153 additionalLinkerInputs := bazel.LabelList{}
Liz Kammere6583482021-10-19 13:56:10 -04001154 if props.Version_script != nil {
1155 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001156 additionalLinkerInputs.Add(&label)
Liz Kammere6583482021-10-19 13:56:10 -04001157 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
1158 }
Alix773adaa2022-04-27 17:49:34 +00001159
1160 if props.Dynamic_list != nil {
1161 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001162 additionalLinkerInputs.Add(&label)
Alix773adaa2022-04-27 17:49:34 +00001163 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1164 }
1165
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001166 la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001167 la.linkopts.SetSelectValue(axis, config, linkerFlags)
Liz Kammere6583482021-10-19 13:56:10 -04001168
1169 if axisFeatures != nil {
1170 la.features.SetSelectValue(axis, config, axisFeatures)
1171 }
Cole Faust6b29f592022-08-09 09:50:56 -07001172
1173 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1174 if !runtimeDeps.IsEmpty() {
1175 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1176 }
Liz Kammere6583482021-10-19 13:56:10 -04001177}
1178
Spandan Das2518c022023-03-17 03:02:32 +00001179var (
1180 apiSurfaceModuleLibCurrentPackage = "@api_surfaces//" + android.ModuleLibApi.String() + "/current:"
1181)
1182
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001183func availableToSameApexes(a, b []string) bool {
1184 if len(a) == 0 && len(b) == 0 {
1185 return true
1186 }
1187 differ, _, _ := android.ListSetDifference(a, b)
1188 return !differ
1189}
1190
Yu Liu10174ff2023-02-21 12:05:26 -08001191func setStubsForDynamicDeps(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis,
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001192 config string, apexAvailable []string, dynamicLibs bazel.LabelList, dynamicDeps *bazel.LabelListAttribute, ind int) {
1193
Yu Liu10174ff2023-02-21 12:05:26 -08001194 depsWithStubs := []bazel.Label{}
1195 for _, l := range dynamicLibs.Includes {
1196 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001197 if d, ok := dep.(*Module); ok && d.HasStubsVariants() {
1198 depApexAvailable := d.ApexAvailable()
1199 if !availableToSameApexes(apexAvailable, depApexAvailable) {
1200 depsWithStubs = append(depsWithStubs, l)
1201 }
Yu Liu10174ff2023-02-21 12:05:26 -08001202 }
1203 }
1204 if len(depsWithStubs) > 0 {
1205 implDynamicDeps := bazel.SubtractBazelLabelList(dynamicLibs, bazel.MakeLabelList(depsWithStubs))
1206 dynamicDeps.SetSelectValue(axis, config, implDynamicDeps)
1207
1208 stubLibLabels := []bazel.Label{}
1209 for _, l := range depsWithStubs {
Spandan Das2518c022023-03-17 03:02:32 +00001210 stubLabelInApiSurfaces := bazel.Label{
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001211 Label: apiSurfaceModuleLibCurrentPackage + strings.TrimPrefix(l.OriginalModuleName, ":"),
Spandan Das2518c022023-03-17 03:02:32 +00001212 }
1213 stubLibLabels = append(stubLibLabels, stubLabelInApiSurfaces)
Yu Liu10174ff2023-02-21 12:05:26 -08001214 }
1215 inApexSelectValue := dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex)
1216 nonApexSelectValue := dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex)
1217 defaultSelectValue := dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
1218 if axis == bazel.NoConfigAxis {
1219 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
1220 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
1221 (&defaultSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
1222 dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1223 dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
1224 dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
1225 } else if config == bazel.OsAndroid {
1226 (&inApexSelectValue).Append(bazel.MakeLabelList(stubLibLabels))
1227 (&nonApexSelectValue).Append(bazel.MakeLabelList(depsWithStubs))
1228 dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1229 dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, bazel.FirstUniqueBazelLabelList(nonApexSelectValue))
1230 }
1231 }
1232}
1233
Jingwen Chen55bc8202021-11-02 06:40:51 +00001234func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001235 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1236 if stripProperties, ok := props.(*StripProperties); ok {
1237 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1238 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1239 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1240 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1241 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001242 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001243 })
Liz Kammere6583482021-10-19 13:56:10 -04001244}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001245
Jingwen Chen55bc8202021-11-02 06:40:51 +00001246func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001247
Liz Kammer47535c52021-06-02 16:02:22 -04001248 type productVarDep struct {
1249 // the name of the corresponding excludes field, if one exists
1250 excludesField string
1251 // reference to the bazel attribute that should be set for the given product variable config
1252 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001253
Jingwen Chen55bc8202021-11-02 06:40:51 +00001254 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001255 }
1256
Zi Wang0a8a1292022-08-30 06:27:01 +00001257 // an intermediate attribute that holds Header_libs info, and will be appended to
1258 // implementationDeps at the end, to solve the confliction that both header_libs
1259 // and static_libs use implementationDeps.
1260 var headerDeps bazel.LabelListAttribute
1261
Liz Kammer47535c52021-06-02 16:02:22 -04001262 productVarToDepFields := map[string]productVarDep{
1263 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001264 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1265 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1266 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001267 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001268 }
1269
Liz Kammer47535c52021-06-02 16:02:22 -04001270 for name, dep := range productVarToDepFields {
1271 props, exists := productVariableProps[name]
1272 excludeProps, excludesExists := productVariableProps[dep.excludesField]
Sasha Smundak39a301c2022-12-29 17:11:49 -08001273 // if neither an include nor excludes property exists, then skip it
Liz Kammer47535c52021-06-02 16:02:22 -04001274 if !exists && !excludesExists {
1275 continue
1276 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001277 // Collect all the configurations that an include or exclude property exists for.
1278 // We want to iterate all configurations rather than either the include or exclude because, for a
1279 // particular configuration, we may have either only an include or an exclude to handle.
1280 productConfigProps := make(map[android.ProductConfigProperty]bool, len(props)+len(excludeProps))
1281 for p := range props {
1282 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001283 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001284 for p := range excludeProps {
1285 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001286 }
1287
Jingwen Chen25825ca2021-11-15 12:28:43 +00001288 for productConfigProp := range productConfigProps {
1289 prop, includesExists := props[productConfigProp]
1290 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001291 var includes, excludes []string
1292 var ok bool
1293 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001294 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001295 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1296 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001297 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001298 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1299 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001300
Jingwen Chen58ff6802021-11-17 12:14:41 +00001301 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001302 dep.attribute.SetSelectValue(
1303 productConfigProp.ConfigurationAxis(),
1304 productConfigProp.SelectKey(),
1305 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1306 )
Liz Kammer47535c52021-06-02 16:02:22 -04001307 }
1308 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001309 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001310}
Liz Kammer47535c52021-06-02 16:02:22 -04001311
Liz Kammer54309532021-12-14 12:21:22 -05001312func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1313 // if system dynamic deps have the default value, any use of a system dynamic library used will
1314 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001315 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001316 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -08001317 toRemove := bazelLabelForSharedDeps(ctx, android.SortedKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001318 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001319 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1320 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001321 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001322 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1323 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001324
1325 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
1326 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndNonApex, toRemove)
1327 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1328 for _, lib := range toRemove.Includes {
Spandan Das2518c022023-03-17 03:02:32 +00001329 stubLabelInApiSurfaces := bazel.Label{
1330 Label: apiSurfaceModuleLibCurrentPackage + lib.OriginalModuleName,
1331 }
1332 stubsToRemove = append(stubsToRemove, stubLabelInApiSurfaces)
Liz Kammer91487d42022-09-13 11:27:11 -04001333 }
1334 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidAndInApex, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001335 }
1336
Liz Kammere6583482021-10-19 13:56:10 -04001337 la.deps.ResolveExcludes()
1338 la.implementationDeps.ResolveExcludes()
1339 la.dynamicDeps.ResolveExcludes()
1340 la.implementationDynamicDeps.ResolveExcludes()
1341 la.wholeArchiveDeps.ResolveExcludes()
1342 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001343
Jingwen Chen91220d72021-03-24 02:18:33 -04001344}
1345
Jingwen Chened9c17d2021-04-13 07:14:55 +00001346// Relativize a list of root-relative paths with respect to the module's
1347// directory.
1348//
1349// include_dirs Soong prop are root-relative (b/183742505), but
1350// local_include_dirs, export_include_dirs and export_system_include_dirs are
1351// module dir relative. This function makes a list of paths entirely module dir
1352// relative.
1353//
1354// For the `include` attribute, Bazel wants the paths to be relative to the
1355// module.
1356func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001357 var relativePaths []string
1358 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001359 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1360 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1361 if err != nil {
1362 panic(err)
1363 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001364 relativePaths = append(relativePaths, relativePath)
1365 }
1366 return relativePaths
1367}
1368
Liz Kammer5fad5012021-09-09 14:08:21 -04001369// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1370// attributes.
1371type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001372 AbsoluteIncludes bazel.StringListAttribute
1373 Includes bazel.StringListAttribute
1374 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001375}
1376
Liz Kammer54549442022-05-11 13:55:06 -04001377func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001378 var exported BazelIncludes
1379 if includes != nil {
1380 exported = *includes
1381 } else {
1382 exported = BazelIncludes{}
1383 }
Zi Wang1cb11802022-12-09 16:08:54 -08001384
1385 // cc library Export_include_dirs and Export_system_include_dirs are marked
1386 // "variant_prepend" in struct tag, set their prepend property to true to make
1387 // sure bp2build generates correct result.
1388 exported.Includes.Prepend = true
1389 exported.SystemIncludes.Prepend = true
1390
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001391 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1392 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1393 if len(flagExporterProperties.Export_include_dirs) > 0 {
1394 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1395 }
1396 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1397 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 -04001398 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001399 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001400 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001401 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001402 exported.Includes.DeduplicateAxesFromBase()
1403 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001404
Liz Kammer5fad5012021-09-09 14:08:21 -04001405 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001406}
Chris Parsons953b3562021-09-20 15:14:39 -04001407
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001408func BazelLabelNameForStaticModule(baseLabel string) string {
1409 return baseLabel + "_bp2build_cc_library_static"
1410}
1411
Jingwen Chen55bc8202021-11-02 06:40:51 +00001412func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001413 label := android.BazelModuleLabel(ctx, m)
Sasha Smundak39a301c2022-12-29 17:11:49 -08001414 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001415 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001416 }
1417 return label
1418}
1419
Jingwen Chen55bc8202021-11-02 06:40:51 +00001420func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001421 // cc_library, at it's root name, propagates the shared library, which depends on the static
1422 // library.
1423 return android.BazelModuleLabel(ctx, m)
1424}
1425
Jingwen Chen55bc8202021-11-02 06:40:51 +00001426func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001427 label := bazelLabelForStaticModule(ctx, m)
1428 if aModule, ok := m.(android.Module); ok {
1429 if android.IsModulePrebuilt(aModule) {
1430 label += "_alwayslink"
1431 }
1432 }
1433 return label
1434}
1435
Jingwen Chen55bc8202021-11-02 06:40:51 +00001436func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001437 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1438}
1439
Jingwen Chen55bc8202021-11-02 06:40:51 +00001440func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001441 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1442}
1443
Jingwen Chen55bc8202021-11-02 06:40:51 +00001444func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001445 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1446}
1447
Jingwen Chen55bc8202021-11-02 06:40:51 +00001448func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001449 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1450}
1451
Jingwen Chen55bc8202021-11-02 06:40:51 +00001452func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001453 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1454}
1455
Jingwen Chen55bc8202021-11-02 06:40:51 +00001456func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001457 // This is not elegant, but bp2build's shared library targets only propagate
1458 // their header information as part of the normal C++ provider.
1459 return bazelLabelForSharedDeps(ctx, modules)
1460}
1461
Zi Wang0a8a1292022-08-30 06:27:01 +00001462func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1463 // This is only used when product_variable header_libs is processed, to follow
1464 // the pattern of depResolutionFunc
1465 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1466}
1467
Jingwen Chen55bc8202021-11-02 06:40:51 +00001468func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001469 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1470}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001471
1472type binaryLinkerAttrs struct {
1473 Linkshared *bool
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001474 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001475}
1476
Jingwen Chen55bc8202021-11-02 06:40:51 +00001477func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001478 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001479 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1480 linkerProps := props.(*BinaryLinkerProperties)
1481 staticExecutable := linkerProps.Static_executable
1482 if axis == bazel.NoConfigAxis {
1483 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1484 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001485 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001486 } else if staticExecutable != nil {
1487 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1488 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1489 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001490 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001491 if suffix := linkerProps.Suffix; suffix != nil {
1492 attrs.Suffix.SetSelectValue(axis, config, suffix)
1493 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001494 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001495
1496 return attrs
1497}
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001498
1499func bp2buildSanitizerFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1500 sanitizerFeatures := bazel.StringListAttribute{}
1501 bp2BuildPropParseHelper(ctx, m, &SanitizeProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1502 var features []string
1503 if sanitizerProps, ok := props.(*SanitizeProperties); ok {
1504 if sanitizerProps.Sanitize.Integer_overflow != nil && *sanitizerProps.Sanitize.Integer_overflow {
1505 features = append(features, "ubsan_integer_overflow")
1506 }
1507 for _, sanitizer := range sanitizerProps.Sanitize.Misc_undefined {
1508 features = append(features, "ubsan_"+sanitizer)
1509 }
1510 sanitizerFeatures.SetSelectValue(axis, config, features)
1511 }
1512 })
1513 return sanitizerFeatures
1514}
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +00001515
1516func bp2buildLtoFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1517 lto_feature_name := "android_thin_lto"
1518 ltoBoolFeatures := bazel.BoolAttribute{}
1519 bp2BuildPropParseHelper(ctx, m, &LTOProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1520 if ltoProps, ok := props.(*LTOProperties); ok {
1521 thinProp := ltoProps.Lto.Thin != nil && *ltoProps.Lto.Thin
1522 thinPropSetToFalse := ltoProps.Lto.Thin != nil && !*ltoProps.Lto.Thin
1523 neverProp := ltoProps.Lto.Never != nil && *ltoProps.Lto.Never
1524 if thinProp {
1525 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(true))
1526 return
1527 }
1528 if neverProp || thinPropSetToFalse {
1529 if thinProp {
1530 ctx.ModuleErrorf("lto.thin and lto.never are mutually exclusive but were specified together")
1531 } else {
1532 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(false))
1533 }
1534 return
1535 }
1536 }
1537 ltoBoolFeatures.SetSelectValue(axis, config, nil)
1538 })
1539
1540 props := m.GetArchVariantProperties(ctx, &LTOProperties{})
1541 ltoStringFeatures, err := ltoBoolFeatures.ToStringListAttribute(func(boolPtr *bool, axis bazel.ConfigurationAxis, config string) []string {
1542 if boolPtr == nil {
1543 return []string{}
1544 }
1545 if !*boolPtr {
1546 return []string{"-" + lto_feature_name}
1547 }
1548 features := []string{lto_feature_name}
1549 if ltoProps, ok := props[axis][config].(*LTOProperties); ok {
1550 if ltoProps.Whole_program_vtables != nil && *ltoProps.Whole_program_vtables {
1551 features = append(features, "android_thin_lto_whole_program_vtables")
1552 }
1553 }
1554 return features
1555 })
1556 if err != nil {
1557 ctx.ModuleErrorf("Error processing LTO attributes: %s", err)
1558 }
1559 return ltoStringFeatures
1560}
Trevor Radcliffea8b44162023-04-14 18:25:24 +00001561
1562func convertHiddenVisibilityToFeatureBase(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1563 visibilityHiddenFeature := bazel.StringListAttribute{}
1564 bp2BuildPropParseHelper(ctx, m, &BaseCompilerProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1565 if baseCompilerProps, ok := props.(*BaseCompilerProperties); ok {
1566 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, baseCompilerProps.Cflags)
1567 }
1568 })
1569 return visibilityHiddenFeature
1570}
1571
1572func convertHiddenVisibilityToFeatureStaticOrShared(ctx android.BazelConversionPathContext, m *Module, isStatic bool) bazel.StringListAttribute {
1573 visibilityHiddenFeature := bazel.StringListAttribute{}
1574 if isStatic {
1575 bp2BuildPropParseHelper(ctx, m, &StaticProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1576 if staticProps, ok := props.(*StaticProperties); ok {
1577 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, staticProps.Static.Cflags)
1578 }
1579 })
1580 } else {
1581 bp2BuildPropParseHelper(ctx, m, &SharedProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1582 if sharedProps, ok := props.(*SharedProperties); ok {
1583 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, sharedProps.Shared.Cflags)
1584 }
1585 })
1586 }
1587
1588 return visibilityHiddenFeature
1589}
1590
1591func convertHiddenVisibilityToFeatureHelper(feature *bazel.StringListAttribute, axis bazel.ConfigurationAxis, configString string, cflags []string) {
1592 if inList(config.VisibilityHiddenFlag, cflags) {
1593 feature.SetSelectValue(axis, configString, []string{"visibility_hidden"})
1594 }
1595}