blob: 5459595e2c38f8ba07a79ed28bb8310aadd7c194 [file] [log] [blame]
Jingwen Chen91220d72021-03-24 02:18:33 -04001// Copyright 2021 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
Cole Faust7071a052022-07-29 15:58:33 -07007// http://www.apache.org/licenses/LICENSE-2.0
Jingwen Chen91220d72021-03-24 02:18:33 -04008//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14package cc
15
16import (
Liz Kammerd2871182021-10-04 13:54:37 -040017 "fmt"
Jingwen Chened9c17d2021-04-13 07:14:55 +000018 "path/filepath"
Jingwen Chen3950cd62021-05-12 04:33:00 +000019 "strings"
Spandan Das4242f102023-04-19 22:31:54 +000020 "sync"
Chris Parsons484e50a2021-05-13 15:13:04 -040021
22 "android/soong/android"
23 "android/soong/bazel"
Alix1be00d42022-05-16 22:56:04 +000024 "android/soong/cc/config"
Liz Kammer7a210ac2021-09-22 15:52:58 -040025
Chris Parsons953b3562021-09-20 15:14:39 -040026 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040027
28 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040029)
30
Liz Kammerae3994e2021-10-19 09:45:48 -040031const (
Trevor Radcliffecee4e052022-09-06 19:31:25 +000032 cSrcPartition = "c"
33 asSrcPartition = "as"
34 asmSrcPartition = "asm"
35 lSrcPartition = "l"
36 llSrcPartition = "ll"
37 cppSrcPartition = "cpp"
38 protoSrcPartition = "proto"
39 aidlSrcPartition = "aidl"
40 syspropSrcPartition = "sysprop"
Alixe2667872023-04-24 14:57:32 +000041
42 yaccSrcPartition = "yacc"
43
44 rScriptSrcPartition = "renderScript"
Liz Kammer91487d42022-09-13 11:27:11 -040045
46 stubsSuffix = "_stub_libs_current"
Liz Kammerae3994e2021-10-19 09:45:48 -040047)
48
Liz Kammer2222c6b2021-05-24 15:41:47 -040049// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000050// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040051type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040052 Srcs bazel.LabelListAttribute
53 Srcs_c bazel.LabelListAttribute
54 Srcs_as bazel.LabelListAttribute
55 Srcs_aidl bazel.LabelListAttribute
56 Hdrs bazel.LabelListAttribute
57 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000058
Liz Kammer12615db2021-09-28 09:19:17 -040059 Deps bazel.LabelListAttribute
60 Implementation_deps bazel.LabelListAttribute
61 Dynamic_deps bazel.LabelListAttribute
62 Implementation_dynamic_deps bazel.LabelListAttribute
63 Whole_archive_deps bazel.LabelListAttribute
64 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070065 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040066
67 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050068
69 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080070
Yu Liuf01a0f02022-12-07 15:45:30 -080071 Native_coverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -070072
Liz Kammeraceec252023-03-24 09:46:36 -040073 Apex_available []string
74
Trevor Radcliffea8b44162023-04-14 18:25:24 +000075 Features bazel.StringListAttribute
76
Yu Liufc603162022-03-01 15:44:08 -080077 sdkAttributes
Sam Delmericofb3bb322022-10-21 10:42:24 -040078
79 tidyAttributes
80}
81
82type tidyAttributes struct {
Sam Delmerico63f0c932023-03-14 14:05:28 -040083 Tidy *string
Sam Delmericofb3bb322022-10-21 10:42:24 -040084 Tidy_flags []string
85 Tidy_checks []string
86 Tidy_checks_as_errors []string
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040087 Tidy_disabled_srcs bazel.LabelListAttribute
Sam Delmerico4c902d62022-11-02 14:17:15 -040088 Tidy_timeout_srcs bazel.LabelListAttribute
Sam Delmericofb3bb322022-10-21 10:42:24 -040089}
90
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040091func (m *Module) convertTidyAttributes(ctx android.BaseMutatorContext, moduleAttrs *tidyAttributes) {
Sam Delmericofb3bb322022-10-21 10:42:24 -040092 for _, f := range m.features {
93 if tidy, ok := f.(*tidyFeature); ok {
Sam Delmerico63f0c932023-03-14 14:05:28 -040094 var tidyAttr *string
95 if tidy.Properties.Tidy != nil {
96 if *tidy.Properties.Tidy {
97 tidyAttr = proptools.StringPtr("local")
98 } else {
99 tidyAttr = proptools.StringPtr("never")
100 }
101 }
102 moduleAttrs.Tidy = tidyAttr
Sam Delmericofb3bb322022-10-21 10:42:24 -0400103 moduleAttrs.Tidy_flags = tidy.Properties.Tidy_flags
104 moduleAttrs.Tidy_checks = tidy.Properties.Tidy_checks
105 moduleAttrs.Tidy_checks_as_errors = tidy.Properties.Tidy_checks_as_errors
106 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400107
108 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400109 archVariantProps := m.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
110 for axis, configToProps := range archVariantProps {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800111 for cfg, _props := range configToProps {
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400112 if archProps, ok := _props.(*BaseCompilerProperties); ok {
113 archDisabledSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_disabled_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800114 moduleAttrs.Tidy_disabled_srcs.SetSelectValue(axis, cfg, archDisabledSrcs)
Sam Delmerico4c902d62022-11-02 14:17:15 -0400115 archTimeoutSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_timeout_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800116 moduleAttrs.Tidy_timeout_srcs.SetSelectValue(axis, cfg, archTimeoutSrcs)
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400117 }
118 }
Sam Delmericofb3bb322022-10-21 10:42:24 -0400119 }
Jingwen Chen53681ef2021-04-29 08:15:13 +0000120}
121
Sam Delmericoc7681022022-02-04 21:01:20 +0000122// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000123func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400124 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
125 // macro.
126 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -0400127 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
128
129 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -0400130 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -0400131 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
132 return labelStr, false
133 }
Yu Liu2aa806b2022-09-01 11:54:47 -0700134 // If the filegroup is already converted to aidl_library or proto_library,
135 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
136 fg, _ := m.(android.FileGroupAsLibrary)
137 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -0400138 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000139 }
Liz Kammer12615db2021-09-28 09:19:17 -0400140 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400141 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000142 }
143
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400144 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +0000145 labels := bazel.LabelPartitions{
146 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500147 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
148 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -0700149 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -0400150 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000151 // TODO(http://b/231968910): If there is ever a filegroup target that
152 // contains .l or .ll files we will need to find a way to add a
153 // LabelMapper for these that identifies these filegroups and
154 // converts them appropriately
Alixe2667872023-04-24 14:57:32 +0000155 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
156 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
157 rScriptSrcPartition: bazel.LabelPartition{Extensions: []string{".fs", ".rscript"}},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400158 // C++ is the "catch-all" group, and comprises generated sources because we don't
159 // know the language of these sources until the genrule is executed.
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000160 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
161 syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
Spandan Dasdf4c2132023-05-09 23:58:52 +0000162 yaccSrcPartition: bazel.LabelPartition{Extensions: []string{".y", "yy"}},
Sam Delmericoc7681022022-02-04 21:01:20 +0000163 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000164
Sam Delmericoc7681022022-02-04 21:01:20 +0000165 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000166}
167
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000168// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000169func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000170 lib, ok := module.compiler.(*libraryDecorator)
171 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400172 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000173 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000174 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
175}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000176
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000177// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000178func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000179 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000180}
181
182// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000183func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000184 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400185}
186
Liz Kammer7a210ac2021-09-22 15:52:58 -0400187type depsPartition struct {
188 export bazel.LabelList
189 implementation bazel.LabelList
190}
191
Jingwen Chen55bc8202021-11-02 06:40:51 +0000192type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400193
Jingwen Chen55bc8202021-11-02 06:40:51 +0000194func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400195 if !exportsDeps {
196 return depsPartition{
197 implementation: fn(ctx, allDeps),
198 }
199 }
200
Liz Kammer7a210ac2021-09-22 15:52:58 -0400201 implementation, export := android.FilterList(allDeps, exportedDeps)
202
203 return depsPartition{
204 export: fn(ctx, export),
205 implementation: fn(ctx, implementation),
206 }
207}
208
Jingwen Chen55bc8202021-11-02 06:40:51 +0000209type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400210
Jingwen Chen55bc8202021-11-02 06:40:51 +0000211func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400212 if !exportsDeps {
213 return depsPartition{
214 implementation: fn(ctx, allDeps, excludes),
215 }
216 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400217 implementation, export := android.FilterList(allDeps, exportedDeps)
218
219 return depsPartition{
220 export: fn(ctx, export, excludes),
221 implementation: fn(ctx, implementation, excludes),
222 }
223}
224
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000225func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
226 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800227 for cfg, props := range configToProps {
228 parseFunc(axis, cfg, props)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000229 }
230 }
231}
232
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000233// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Liz Kammeraceec252023-03-24 09:46:36 -0400234func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400235 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000236
Liz Kammer9abd62d2021-05-21 08:37:59 -0400237 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000238 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutHiddenVisibility))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000239 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400240 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400241
Liz Kammer2b8004b2021-10-04 13:55:44 -0400242 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400243 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
244 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
245
Liz Kammer2b8004b2021-10-04 13:55:44 -0400246 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400247 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
248 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
249
250 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500251 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000252 }
Liz Kammer135bf552021-08-11 10:46:06 -0400253 // system_dynamic_deps distinguishes between nil/empty list behavior:
254 // nil -> use default values
255 // empty list -> no values specified
256 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000257
Liz Kammeraceec252023-03-24 09:46:36 -0400258 var apexAvailable []string
Jingwen Chenbcf53042021-05-26 04:42:42 +0000259 if isStatic {
Liz Kammeraceec252023-03-24 09:46:36 -0400260 apexAvailable = lib.StaticProperties.Static.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000261 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
262 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
263 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000264 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000265 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000266 } else {
Liz Kammeraceec252023-03-24 09:46:36 -0400267 apexAvailable = lib.SharedProperties.Shared.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000268 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
269 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
270 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000271 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000272 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000273 }
274
Liz Kammerae3994e2021-10-19 09:45:48 -0400275 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
276 attrs.Srcs = partitionedSrcs[cppSrcPartition]
277 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
278 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000279
Spandan Das39b6cc52023-04-12 19:05:49 +0000280 attrs.Apex_available = android.ConvertApexAvailableToTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), apexAvailable)
Liz Kammeraceec252023-03-24 09:46:36 -0400281
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000282 attrs.Features.Append(convertHiddenVisibilityToFeatureStaticOrShared(ctx, module, isStatic))
283
Liz Kammer12615db2021-09-28 09:19:17 -0400284 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
285 // TODO(b/208815215): determine whether this is used and add support if necessary
286 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
287 }
288
Jingwen Chenbcf53042021-05-26 04:42:42 +0000289 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000290}
291
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400292// Convenience struct to hold all attributes parsed from prebuilt properties.
293type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000294 Src bazel.LabelAttribute
295 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400296}
297
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000298func parseSrc(ctx android.BazelConversionPathContext, srcLabelAttribute *bazel.LabelAttribute, axis bazel.ConfigurationAxis, config string, srcs []string) {
299 srcFileError := func() {
300 ctx.ModuleErrorf("parseSrc: Expected at most one source file for %s %s\n", axis, config)
301 }
302 if len(srcs) > 1 {
303 srcFileError()
304 return
305 } else if len(srcs) == 0 {
306 return
307 }
308 if srcLabelAttribute.SelectValue(axis, config) != nil {
309 srcFileError()
310 return
311 }
312 srcLabelAttribute.SetSelectValue(axis, config, android.BazelLabelForModuleSrcSingle(ctx, srcs[0]))
313}
314
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000315// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000316func 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 +0000317
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400318 var srcLabelAttribute bazel.LabelAttribute
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000319 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
320 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000321 parseSrc(ctx, &srcLabelAttribute, axis, config, prebuiltLinkerProperties.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000322 }
323 })
324
325 var enabledLabelAttribute bazel.BoolAttribute
326 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
327 if props.Enabled != nil {
328 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
329 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000330 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000331 }
332
333 if isStatic {
334 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
335 if staticProperties, ok := props.(*StaticProperties); ok {
336 parseAttrs(axis, config, staticProperties.Static)
337 }
338 })
339 } else {
340 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
341 if sharedProperties, ok := props.(*SharedProperties); ok {
342 parseAttrs(axis, config, sharedProperties.Shared)
343 }
344 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400345 }
346
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400347 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000348 Src: srcLabelAttribute,
349 Enabled: enabledLabelAttribute,
350 }
351}
352
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000353func bp2BuildParsePrebuiltBinaryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
354 var srcLabelAttribute bazel.LabelAttribute
355 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
356 if props, ok := props.(*prebuiltLinkerProperties); ok {
357 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000358 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000359 })
360
361 return prebuiltAttributes{
362 Src: srcLabelAttribute,
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400363 }
364}
365
Colin Crossc5075e92022-12-05 16:46:39 -0800366func bp2BuildParsePrebuiltObjectProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
367 var srcLabelAttribute bazel.LabelAttribute
368 bp2BuildPropParseHelper(ctx, module, &prebuiltObjectProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
369 if props, ok := props.(*prebuiltObjectProperties); ok {
370 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
371 }
372 })
373
374 return prebuiltAttributes{
375 Src: srcLabelAttribute,
376 }
377}
378
Liz Kammere6583482021-10-19 13:56:10 -0400379type baseAttributes struct {
380 compilerAttributes
381 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400382
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000383 // A combination of compilerAttributes.features and linkerAttributes.features, as well as sanitizer features
Cole Faust5fa4e962022-08-22 14:31:04 -0700384 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400385 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400386 aidlDependency *bazel.LabelAttribute
Yu Liuf01a0f02022-12-07 15:45:30 -0800387 Native_coverage *bool
Liz Kammere6583482021-10-19 13:56:10 -0400388}
389
Jingwen Chen107c0de2021-04-09 10:43:12 +0000390// Convenience struct to hold all attributes parsed from compiler properties.
391type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400392 // Options for all languages
393 copts bazel.StringListAttribute
394 // Assembly options and sources
395 asFlags bazel.StringListAttribute
396 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700397 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400398 // C options and sources
399 conlyFlags bazel.StringListAttribute
400 cSrcs bazel.LabelListAttribute
401 // C++ options and sources
402 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000403 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400404
Liz Kammer084d6a92023-06-22 16:23:53 -0400405 // xsd config sources
406 xsdInSrcs bazel.StringListAttribute
407
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000408 // Lex sources and options
409 lSrcs bazel.LabelListAttribute
410 llSrcs bazel.LabelListAttribute
411 lexopts bazel.StringListAttribute
412
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000413 // Sysprop sources
414 syspropSrcs bazel.LabelListAttribute
415
Spandan Dasdf4c2132023-05-09 23:58:52 +0000416 // Yacc sources
417 yaccSrc *bazel.LabelAttribute
418 yaccFlags bazel.StringListAttribute
419 yaccGenLocationHeader bazel.BoolAttribute
420 yaccGenPositionHeader bazel.BoolAttribute
421
Alixe2667872023-04-24 14:57:32 +0000422 rsSrcs bazel.LabelListAttribute
423
Liz Kammere6583482021-10-19 13:56:10 -0400424 hdrs bazel.LabelListAttribute
425
Chris Parsons2c788392021-08-10 11:58:07 -0400426 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000427
428 // Not affected by arch variants
429 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500430 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000431 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400432
433 localIncludes bazel.StringListAttribute
434 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400435
Liz Kammer1263d9b2021-12-10 14:28:20 -0500436 includes BazelIncludes
437
Alixe2667872023-04-24 14:57:32 +0000438 protoSrcs bazel.LabelListAttribute
439 aidlSrcs bazel.LabelListAttribute
440 rscriptSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000441
442 stubsSymbolFile *string
443 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700444
445 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500446
Spandan Das39ccf932023-05-26 18:03:39 +0000447 stem bazel.StringAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500448 suffix bazel.StringAttribute
Vinh Tran99270ea2022-11-28 11:15:23 -0500449
450 fdoProfile bazel.LabelAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000451}
452
Liz Kammercac7f692021-12-16 14:19:32 -0500453type filterOutFn func(string) bool
454
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000455// filterOutHiddenVisibility removes the flag specifying hidden visibility as
456// this flag is converted to a toolchain feature
457func filterOutHiddenVisibility(flag string) bool {
458 return flag == config.VisibilityHiddenFlag
459}
460
Liz Kammercac7f692021-12-16 14:19:32 -0500461func filterOutStdFlag(flag string) bool {
462 return strings.HasPrefix(flag, "-std=")
463}
464
Alix1be00d42022-05-16 22:56:04 +0000465func filterOutClangUnknownCflags(flag string) bool {
466 for _, f := range config.ClangUnknownCflags {
467 if f == flag {
468 return true
469 }
470 }
471 return false
472}
473
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000474func parseCommandLineFlags(soongFlags []string, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400475 var result []string
476 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000477 skipFlag := false
478 for _, filter := range filterOut {
479 if filter != nil && filter(flag) {
480 skipFlag = true
481 }
482 }
483 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500484 continue
485 }
Liz Kammere6583482021-10-19 13:56:10 -0400486 // Soong's cflags can contain spaces, like `-include header.h`. For
487 // Bazel's copts, split them up to be compatible with the
488 // no_copts_tokenization feature.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000489 result = append(result, strings.Split(flag, " ")...)
Liz Kammere6583482021-10-19 13:56:10 -0400490 }
491 return result
492}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000493
Jingwen Chen55bc8202021-11-02 06:40:51 +0000494func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400495 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
496 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
Liz Kammer084d6a92023-06-22 16:23:53 -0400497 srcsList, xsdList, ok := parseSrcs(ctx, props)
498
499 if ok {
Liz Kammere6583482021-10-19 13:56:10 -0400500 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400501 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400502 if len(xsdList) > 0 {
503 ca.xsdInSrcs.SetSelectValue(axis, config, xsdList)
504 }
Chris Parsons990c4f42021-05-25 12:10:58 -0400505
Liz Kammere6583482021-10-19 13:56:10 -0400506 localIncludeDirs := props.Local_include_dirs
507 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500508 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400509 if includeBuildDirectory(props.Include_build_directory) {
510 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400511 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000512 }
513
Liz Kammere6583482021-10-19 13:56:10 -0400514 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
515 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
516
Cole Faust5fa4e962022-08-22 14:31:04 -0700517 instructionSet := proptools.StringDefault(props.Instruction_set, "")
518 if instructionSet == "arm" {
Trevor Radcliffe5f0c2ac2023-05-15 18:00:59 +0000519 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm"})
Cole Faust5fa4e962022-08-22 14:31:04 -0700520 } else if instructionSet != "" && instructionSet != "thumb" {
521 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
522 }
523
Liz Kammercac7f692021-12-16 14:19:32 -0500524 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
525 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
526 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
527 // cases.
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000528 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutClangUnknownCflags, filterOutHiddenVisibility))
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000529 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
530 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, filterOutClangUnknownCflags))
531 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400532 ca.rtti.SetSelectValue(axis, config, props.Rtti)
533}
534
Jingwen Chen55bc8202021-11-02 06:40:51 +0000535func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000536 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
537 if stlProps, ok := props.(*StlProperties); ok {
538 if stlProps.Stl == nil {
539 return
540 }
541 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400542 stl := deduplicateStlInput(*stlProps.Stl)
543 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000544 } else if ca.stl != stlProps.Stl {
545 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 -0400546 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000547 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000548 })
Liz Kammere6583482021-10-19 13:56:10 -0400549}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000550
Jingwen Chen55bc8202021-11-02 06:40:51 +0000551func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400552 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400553 "Cflags": &ca.copts,
554 "Asflags": &ca.asFlags,
Yu Liu93893ba2023-05-01 13:49:52 -0700555 "Cppflags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400556 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400557 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000558 if productConfigProps, exists := productVariableProps[propName]; exists {
559 for productConfigProp, prop := range productConfigProps {
560 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400561 if !ok {
562 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
563 }
Cole Faust150f9a52023-04-26 10:52:24 -0700564 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name())
Jingwen Chen25825ca2021-11-15 12:28:43 +0000565 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400566 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400567 }
568 }
Liz Kammere6583482021-10-19 13:56:10 -0400569}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400570
Jingwen Chen55bc8202021-11-02 06:40:51 +0000571func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400572 ca.srcs.ResolveExcludes()
573 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
574
Liz Kammer12615db2021-09-28 09:19:17 -0400575 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400576 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400577
Liz Kammere6583482021-10-19 13:56:10 -0400578 for p, lla := range partitionedSrcs {
579 // if there are no sources, there is no need for headers
580 if lla.IsEmpty() {
581 continue
582 }
583 lla.Append(implementationHdrs)
584 partitionedSrcs[p] = lla
585 }
586
587 ca.srcs = partitionedSrcs[cppSrcPartition]
588 ca.cSrcs = partitionedSrcs[cSrcPartition]
589 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700590 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000591 ca.lSrcs = partitionedSrcs[lSrcPartition]
592 ca.llSrcs = partitionedSrcs[llSrcPartition]
Spandan Dasdf4c2132023-05-09 23:58:52 +0000593 if yacc := partitionedSrcs[yaccSrcPartition]; !yacc.IsEmpty() {
594 if len(yacc.Value.Includes) > 1 {
595 ctx.PropertyErrorf("srcs", "Found multiple yacc (.y/.yy) files in library")
596 }
597 ca.yaccSrc = bazel.MakeLabelAttribute(yacc.Value.Includes[0].Label)
598 }
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000599 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
Alixe2667872023-04-24 14:57:32 +0000600 ca.rscriptSrcs = partitionedSrcs[rScriptSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400601
602 ca.absoluteIncludes.DeduplicateAxesFromBase()
603 ca.localIncludes.DeduplicateAxesFromBase()
604}
605
606// Parse srcs from an arch or OS's props value.
Liz Kammer084d6a92023-06-22 16:23:53 -0400607func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, []string, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400608 anySrcs := false
609 // Add srcs-like dependencies such as generated files.
610 // First create a LabelList containing these dependencies, then merge the values with srcs.
Liz Kammer084d6a92023-06-22 16:23:53 -0400611 genSrcs, xsd := android.PartitionXsdSrcs(ctx, props.Generated_sources)
Spandan Das922171d2023-05-31 23:32:40 +0000612 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, genSrcs, props.Exclude_generated_sources)
Liz Kammere6583482021-10-19 13:56:10 -0400613 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
614 anySrcs = true
615 }
616
617 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400618
Liz Kammere6583482021-10-19 13:56:10 -0400619 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
620 anySrcs = true
621 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400622
Liz Kammer084d6a92023-06-22 16:23:53 -0400623 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), xsd, anySrcs
Liz Kammere6583482021-10-19 13:56:10 -0400624}
625
Liz Kammera5a29de2022-05-25 23:19:37 -0400626func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
627 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500628 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
629 // Defaults are handled by the toolchain definition.
630 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400631 stdVal := proptools.StringDefault(std, defaultVal)
632 if stdVal == "experimental" || stdVal == defaultVal {
633 if stdVal == "experimental" {
634 stdVal = prefix + "_std_experimental"
635 }
636 if !useGnu {
637 stdVal += "_no_gnu"
638 }
639 } else if !useGnu {
640 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500641 }
642
Liz Kammera5a29de2022-05-25 23:19:37 -0400643 if stdVal == defaultVal {
644 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500645 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400646 return &stdVal
647}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500648
Liz Kammera5a29de2022-05-25 23:19:37 -0400649func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
650 useGnu := useGnuExtensions(gnu_extensions)
651
652 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400653}
654
Liz Kammer1263d9b2021-12-10 14:28:20 -0500655// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
656// is fully-qualified.
657// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
658func packageFromLabel(label string) (string, bool) {
659 split := strings.Split(label, ":")
660 if len(split) != 2 {
661 return "", false
662 }
663 if split[0] == "" {
664 return ".", false
665 }
666 // remove leading "//"
667 return split[0][2:], true
668}
669
670// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList>
671func includesFromLabelList(labelList bazel.LabelList) (relative, absolute []string) {
672 for _, hdr := range labelList.Includes {
673 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
674 absolute = append(absolute, pkg)
675 } else if pkg != "" {
676 relative = append(relative, pkg)
677 }
678 }
679 return relative, absolute
680}
681
Cole Faust7071a052022-07-29 15:58:33 -0700682type YasmAttributes struct {
683 Srcs bazel.LabelListAttribute
684 Flags bazel.StringListAttribute
685 Include_dirs bazel.StringListAttribute
686}
687
688func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
689 if ca.asmSrcs.IsEmpty() {
690 return nil
691 }
692
693 // Yasm needs the include directories from both local_includes and
694 // export_include_dirs. We don't care about actually exporting them from the
695 // yasm rule though, because they will also be present on the cc_ rule that
696 // wraps this yasm rule.
697 includes := ca.localIncludes.Clone()
698 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
699 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
700 if len(flagExporterProperties.Export_include_dirs) > 0 {
701 x := bazel.StringListAttribute{}
702 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
703 includes.Append(x)
704 }
705 }
706 })
707
708 ctx.CreateBazelTargetModule(
709 bazel.BazelTargetModuleProperties{
710 Rule_class: "yasm",
711 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
712 },
713 android.CommonAttributes{Name: m.Name() + "_yasm"},
714 &YasmAttributes{
715 Srcs: ca.asmSrcs,
716 Flags: ca.asFlags,
717 Include_dirs: *includes,
718 })
719
720 // We only want to add a dependency on the _yasm target if there are asm
721 // sources in the current configuration. If there are unconfigured asm
722 // sources, always add the dependency. Otherwise, add the dependency only
723 // on the configuration axes and values that had asm sources.
724 if len(ca.asmSrcs.Value.Includes) > 0 {
725 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
726 }
727
728 ret := &bazel.LabelAttribute{}
729 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800730 for cfg := range ca.asmSrcs.ConfigurableValues[axis] {
731 ret.SetSelectValue(axis, cfg, bazel.Label{Label: ":" + m.Name() + "_yasm"})
Cole Faust7071a052022-07-29 15:58:33 -0700732 }
733 }
734 return ret
735}
736
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000737// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400738func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400739 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
740 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000741 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400742
743 var implementationHdrs bazel.LabelListAttribute
744
745 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
746 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
747 for axis, configMap := range cp {
748 if _, ok := axisToConfigs[axis]; !ok {
749 axisToConfigs[axis] = map[string]bool{}
750 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800751 for cfg := range configMap {
752 axisToConfigs[axis][cfg] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400753 }
754 }
755 }
Liz Kammere6583482021-10-19 13:56:10 -0400756 allAxesAndConfigs(archVariantCompilerProps)
757 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000758 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400759
Liz Kammere6583482021-10-19 13:56:10 -0400760 compilerAttrs := compilerAttributes{}
761 linkerAttrs := linkerAttributes{}
762
Vinh Tran367d89d2023-04-28 11:21:25 -0400763 var aidlLibs bazel.LabelList
764
Chris Parsons7b3289b2023-01-26 17:30:44 -0500765 // Iterate through these axes in a deterministic order. This is required
766 // because processing certain dependencies may result in concatenating
767 // elements along other axes. (For example, processing NoConfig may result
768 // in elements being added to InApex). This is thus the only way to ensure
769 // that the order of entries in each list is in a predictable order.
770 for _, axis := range bazel.SortedConfigurationAxes(axisToConfigs) {
771 configs := axisToConfigs[axis]
Sasha Smundak39a301c2022-12-29 17:11:49 -0800772 for cfg := range configs {
Liz Kammer084d6a92023-06-22 16:23:53 -0400773 var allHdrs, allHdrsXsd []string
Sasha Smundak39a301c2022-12-29 17:11:49 -0800774 if baseCompilerProps, ok := archVariantCompilerProps[axis][cfg].(*BaseCompilerProperties); ok {
Liz Kammer084d6a92023-06-22 16:23:53 -0400775 allHdrs, allHdrsXsd = android.PartitionXsdSrcs(ctx, baseCompilerProps.Generated_headers)
Spandan Das922171d2023-05-31 23:32:40 +0000776
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000777 if baseCompilerProps.Lex != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800778 compilerAttrs.lexopts.SetSelectValue(axis, cfg, baseCompilerProps.Lex.Flags)
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000779 }
Spandan Dasdf4c2132023-05-09 23:58:52 +0000780 if baseCompilerProps.Yacc != nil {
781 compilerAttrs.yaccFlags.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Flags)
782 compilerAttrs.yaccGenLocationHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_location_hh)
783 compilerAttrs.yaccGenPositionHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_position_hh)
784 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800785 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, cfg, baseCompilerProps)
Vinh Tran367d89d2023-04-28 11:21:25 -0400786 aidlLibs.Append(android.BazelLabelForModuleDeps(ctx, baseCompilerProps.Aidl.Libs))
Liz Kammere6583482021-10-19 13:56:10 -0400787 }
788
Liz Kammer084d6a92023-06-22 16:23:53 -0400789 var exportHdrs, exportHdrsXsd []string
Liz Kammere6583482021-10-19 13:56:10 -0400790
Sasha Smundak39a301c2022-12-29 17:11:49 -0800791 if baseLinkerProps, ok := archVariantLinkerProps[axis][cfg].(*BaseLinkerProperties); ok {
Liz Kammer084d6a92023-06-22 16:23:53 -0400792 exportHdrs, exportHdrsXsd = android.PartitionXsdSrcs(ctx, baseLinkerProps.Export_generated_headers)
Liz Kammer48cdbeb2023-03-17 10:17:50 -0400793 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module, axis, cfg, baseLinkerProps)
Liz Kammere6583482021-10-19 13:56:10 -0400794 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400795
796 // in the synthetic bp2build workspace, xsd sources are compiled to a static library
797 xsdList := compilerAttrs.xsdInSrcs.SelectValue(axis, cfg)
798 allHdrsXsd = android.FirstUniqueStrings(append(xsdList, allHdrsXsd...))
Liz Kammere6583482021-10-19 13:56:10 -0400799 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportHdrs, android.BazelLabelForModuleDeps)
Liz Kammer084d6a92023-06-22 16:23:53 -0400800 xsdConfigLibs := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrsXsd, exportHdrsXsd, bazelLabelForXsdConfig)
801
Sasha Smundak39a301c2022-12-29 17:11:49 -0800802 implementationHdrs.SetSelectValue(axis, cfg, headers.implementation)
803 compilerAttrs.hdrs.SetSelectValue(axis, cfg, headers.export)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500804
805 exportIncludes, exportAbsoluteIncludes := includesFromLabelList(headers.export)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800806 compilerAttrs.includes.Includes.SetSelectValue(axis, cfg, exportIncludes)
807 compilerAttrs.includes.AbsoluteIncludes.SetSelectValue(axis, cfg, exportAbsoluteIncludes)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500808
809 includes, absoluteIncludes := includesFromLabelList(headers.implementation)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800810 currAbsoluteIncludes := compilerAttrs.absoluteIncludes.SelectValue(axis, cfg)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500811 currAbsoluteIncludes = android.FirstUniqueStrings(append(currAbsoluteIncludes, absoluteIncludes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400812
Sasha Smundak39a301c2022-12-29 17:11:49 -0800813 compilerAttrs.absoluteIncludes.SetSelectValue(axis, cfg, currAbsoluteIncludes)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400814
Sasha Smundak39a301c2022-12-29 17:11:49 -0800815 currIncludes := compilerAttrs.localIncludes.SelectValue(axis, cfg)
Liz Kammer1263d9b2021-12-10 14:28:20 -0500816 currIncludes = android.FirstUniqueStrings(append(currIncludes, includes...))
Vinh Tran9f6796a2022-08-16 13:10:31 -0400817
Sasha Smundak39a301c2022-12-29 17:11:49 -0800818 compilerAttrs.localIncludes.SetSelectValue(axis, cfg, currIncludes)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000819
Sasha Smundak39a301c2022-12-29 17:11:49 -0800820 if libraryProps, ok := archVariantLibraryProperties[axis][cfg].(*LibraryProperties); ok {
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000821 if axis == bazel.NoConfigAxis {
Sam Delmerico75dbca22023-04-20 13:13:25 +0000822 if libraryProps.Stubs.Symbol_file != nil {
823 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
824 versions := android.CopyOf(libraryProps.Stubs.Versions)
825 normalizeVersions(ctx, versions)
826 versions = addCurrentVersionIfNotPresent(versions)
827 compilerAttrs.stubsVersions.SetSelectValue(axis, cfg, versions)
828 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000829 }
Spandan Das39ccf932023-05-26 18:03:39 +0000830 if stem := libraryProps.Stem; stem != nil {
831 compilerAttrs.stem.SetSelectValue(axis, cfg, stem)
832 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500833 if suffix := libraryProps.Suffix; suffix != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800834 compilerAttrs.suffix.SetSelectValue(axis, cfg, suffix)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500835 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000836 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400837
838 if len(allHdrsXsd) > 0 {
839 wholeStaticLibs := linkerAttrs.implementationWholeArchiveDeps.SelectValue(axis, cfg)
840 (&wholeStaticLibs).Append(xsdConfigLibs.implementation)
841 linkerAttrs.implementationWholeArchiveDeps.SetSelectValue(axis, cfg, wholeStaticLibs)
842 wholeStaticLibs = linkerAttrs.wholeArchiveDeps.SelectValue(axis, cfg)
843 (&wholeStaticLibs).Append(xsdConfigLibs.export)
844 linkerAttrs.wholeArchiveDeps.SetSelectValue(axis, cfg, wholeStaticLibs)
845 }
Liz Kammere6583482021-10-19 13:56:10 -0400846 }
847 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400848
Liz Kammere6583482021-10-19 13:56:10 -0400849 compilerAttrs.convertStlProps(ctx, module)
850 (&linkerAttrs).convertStripProps(ctx, module)
851
Yu Liuf01a0f02022-12-07 15:45:30 -0800852 var nativeCoverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -0700853 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
854 !Bool(module.coverage.Properties.Native_coverage) {
Yu Liuf01a0f02022-12-07 15:45:30 -0800855 nativeCoverage = BoolPtr(false)
Yu Liu8d82ac52022-05-17 15:13:28 -0700856 }
857
Cole Faust912bc882023-03-08 12:29:50 -0800858 productVariableProps := android.ProductVariableProperties(ctx, ctx.Module())
Liz Kammere6583482021-10-19 13:56:10 -0400859
860 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
861 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
862
863 (&compilerAttrs).finalize(ctx, implementationHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500864 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400865
Cole Faust7071a052022-07-29 15:58:33 -0700866 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
867
Liz Kammer12615db2021-09-28 09:19:17 -0400868 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
869
870 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
871 // which. This will add the newly generated proto library to the appropriate attribute and nothing
872 // to the other
873 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
874 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400875
Vinh Tran367d89d2023-04-28 11:21:25 -0400876 aidlDep := bp2buildCcAidlLibrary(
877 ctx, module,
878 compilerAttrs.aidlSrcs,
879 bazel.LabelListAttribute{
880 Value: aidlLibs,
881 },
882 linkerAttrs,
Vinh Trane6842942023-04-28 11:21:25 -0400883 compilerAttrs,
Vinh Tran367d89d2023-04-28 11:21:25 -0400884 )
Vinh Tranfde57eb2022-08-29 17:46:58 -0400885 if aidlDep != nil {
886 if lib, ok := module.linker.(*libraryDecorator); ok {
887 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
888 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
889 } else {
890 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
891 }
892 }
893 }
Liz Kammer12615db2021-09-28 09:19:17 -0400894
Spandan Dasdf4c2132023-05-09 23:58:52 +0000895 // Create a cc_yacc_static_library if srcs contains .y/.yy files
896 // This internal target will produce an .a file that will be statically linked to the parent library
897 if yaccDep := bp2buildCcYaccLibrary(ctx, compilerAttrs, linkerAttrs); yaccDep != nil {
898 (&linkerAttrs).implementationWholeArchiveDeps.Add(yaccDep)
899 }
900
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000901 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
902 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
903 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
904
Vinh Tran99270ea2022-11-28 11:15:23 -0500905 if module.afdo != nil && module.afdo.Properties.Afdo {
906 fdoProfileDep := bp2buildFdoProfile(ctx, module)
907 if fdoProfileDep != nil {
908 (&compilerAttrs).fdoProfile.SetValue(*fdoProfileDep)
909 }
910 }
911
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000912 if !compilerAttrs.syspropSrcs.IsEmpty() {
913 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
914 }
915
Zi Wang9f609db2023-01-04 11:06:54 -0800916 linkerAttrs.wholeArchiveDeps.Prepend = true
917 linkerAttrs.deps.Prepend = true
918 compilerAttrs.localIncludes.Prepend = true
919 compilerAttrs.absoluteIncludes.Prepend = true
920 compilerAttrs.hdrs.Prepend = true
921
Alixe2667872023-04-24 14:57:32 +0000922 convertedRsSrcs, rsAbsIncludes, rsLocalIncludes := bp2buildRScript(ctx, module, compilerAttrs)
923 (&compilerAttrs).srcs.Add(&convertedRsSrcs)
924 (&compilerAttrs).absoluteIncludes.Append(rsAbsIncludes)
925 (&compilerAttrs).localIncludes.Append(rsLocalIncludes)
926 (&compilerAttrs).localIncludes.Value = android.FirstUniqueStrings(compilerAttrs.localIncludes.Value)
927
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000928 features := compilerAttrs.features.Clone().Append(linkerAttrs.features).Append(bp2buildSanitizerFeatures(ctx, module))
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +0000929 features = features.Append(bp2buildLtoFeatures(ctx, module))
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000930 features = features.Append(convertHiddenVisibilityToFeatureBase(ctx, module))
Cole Faust5fa4e962022-08-22 14:31:04 -0700931 features.DeduplicateAxesFromBase()
932
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +0000933 addMuslSystemDynamicDeps(ctx, linkerAttrs)
934
Liz Kammere6583482021-10-19 13:56:10 -0400935 return baseAttributes{
936 compilerAttrs,
937 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700938 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400939 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400940 aidlDep,
Yu Liuf01a0f02022-12-07 15:45:30 -0800941 nativeCoverage,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000942 }
943}
944
Spandan Dasdf4c2132023-05-09 23:58:52 +0000945type ccYaccLibraryAttributes struct {
946 Src bazel.LabelAttribute
947 Flags bazel.StringListAttribute
948 Gen_location_hh bazel.BoolAttribute
949 Gen_position_hh bazel.BoolAttribute
950 Local_includes bazel.StringListAttribute
951 Implementation_deps bazel.LabelListAttribute
952 Implementation_dynamic_deps bazel.LabelListAttribute
953}
954
955func bp2buildCcYaccLibrary(ctx android.Bp2buildMutatorContext, ca compilerAttributes, la linkerAttributes) *bazel.LabelAttribute {
956 if ca.yaccSrc == nil {
957 return nil
958 }
959 yaccLibraryLabel := ctx.Module().Name() + "_yacc"
960 ctx.CreateBazelTargetModule(
961 bazel.BazelTargetModuleProperties{
962 Rule_class: "cc_yacc_static_library",
963 Bzl_load_location: "//build/bazel/rules/cc:cc_yacc_library.bzl",
964 },
965 android.CommonAttributes{
966 Name: yaccLibraryLabel,
967 },
968 &ccYaccLibraryAttributes{
969 Src: *ca.yaccSrc,
970 Flags: ca.yaccFlags,
971 Gen_location_hh: ca.yaccGenLocationHeader,
972 Gen_position_hh: ca.yaccGenPositionHeader,
973 Local_includes: ca.localIncludes,
974 Implementation_deps: la.implementationDeps,
975 Implementation_dynamic_deps: la.implementationDynamicDeps,
976 },
977 )
978
979 yaccLibrary := &bazel.LabelAttribute{
980 Value: &bazel.Label{
981 Label: ":" + yaccLibraryLabel,
982 },
983 }
984 return yaccLibrary
985}
986
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +0000987// As a workaround for b/261657184, we are manually adding the default value
988// of system_dynamic_deps for the linux_musl os.
989// TODO: Solve this properly
990func addMuslSystemDynamicDeps(ctx android.Bp2buildMutatorContext, attrs linkerAttributes) {
991 systemDynamicDeps := attrs.systemDynamicDeps.SelectValue(bazel.OsConfigurationAxis, "linux_musl")
992 if attrs.systemDynamicDeps.HasAxisSpecificValues(bazel.OsConfigurationAxis) && systemDynamicDeps.IsNil() {
993 attrs.systemDynamicDeps.SetSelectValue(bazel.OsConfigurationAxis, "linux_musl", android.BazelLabelForModuleDeps(ctx, config.MuslDefaultSharedLibraries))
994 }
995}
996
Vinh Tran99270ea2022-11-28 11:15:23 -0500997type fdoProfileAttributes struct {
998 Absolute_path_profile string
999}
1000
1001func bp2buildFdoProfile(
1002 ctx android.Bp2buildMutatorContext,
1003 m *Module,
1004) *bazel.Label {
1005 for _, project := range globalAfdoProfileProjects {
Vinh Tranbc9c8b42022-12-09 12:03:52 -05001006 // Ensure handcrafted BUILD file exists in the project
1007 BUILDPath := android.ExistentPathForSource(ctx, project, "BUILD")
1008 if BUILDPath.Valid() {
1009 // We handcraft a BUILD file with fdo_profile targets that use the existing profiles in the project
1010 // This implementation is assuming that every afdo profile in globalAfdoProfileProjects already has
1011 // an associated fdo_profile target declared in the same package.
1012 // TODO(b/260714900): Handle arch-specific afdo profiles (e.g. `<module-name>-arm<64>.afdo`)
1013 path := android.ExistentPathForSource(ctx, project, m.Name()+".afdo")
1014 if path.Valid() {
1015 // FIXME: Some profiles only exist internally and are not released to AOSP.
1016 // When generated BUILD files are checked in, we'll run into merge conflict.
1017 // The cc_library_shared target in AOSP won't have reference to an fdo_profile target because
1018 // the profile doesn't exist. Internally, the same cc_library_shared target will
1019 // have reference to the fdo_profile.
1020 // For more context, see b/258682955#comment2
1021 fdoProfileLabel := "//" + strings.TrimSuffix(project, "/") + ":" + m.Name()
1022 return &bazel.Label{
1023 Label: fdoProfileLabel,
1024 }
Vinh Tran99270ea2022-11-28 11:15:23 -05001025 }
1026 }
1027 }
1028
1029 return nil
1030}
1031
Vinh Tran9f6796a2022-08-16 13:10:31 -04001032func bp2buildCcAidlLibrary(
1033 ctx android.Bp2buildMutatorContext,
1034 m *Module,
Vinh Tran367d89d2023-04-28 11:21:25 -04001035 aidlSrcs bazel.LabelListAttribute,
1036 aidlLibs bazel.LabelListAttribute,
Vinh Tran395a1e92022-09-16 18:27:29 -04001037 linkerAttrs linkerAttributes,
Vinh Trane6842942023-04-28 11:21:25 -04001038 compilerAttrs compilerAttributes,
Vinh Tran9f6796a2022-08-16 13:10:31 -04001039) *bazel.LabelAttribute {
Vinh Tran367d89d2023-04-28 11:21:25 -04001040 var aidlLibsFromSrcs, aidlFiles bazel.LabelListAttribute
1041 apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), ctx.Module())
1042
1043 if !aidlSrcs.IsEmpty() {
1044 aidlLibsFromSrcs, aidlFiles = aidlSrcs.Partition(func(src bazel.Label) bool {
Vinh Trana3b8b782022-09-14 11:40:24 -04001045 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
1046 fg.ShouldConvertToAidlLibrary(ctx) {
1047 return true
1048 }
1049 return false
1050 })
Vinh Tran9f6796a2022-08-16 13:10:31 -04001051
Vinh Tran367d89d2023-04-28 11:21:25 -04001052 if !aidlFiles.IsEmpty() {
Vinh Trana3b8b782022-09-14 11:40:24 -04001053 aidlLibName := m.Name() + "_aidl_library"
1054 ctx.CreateBazelTargetModule(
1055 bazel.BazelTargetModuleProperties{
1056 Rule_class: "aidl_library",
Sam Delmericoe55bf082023-03-31 09:47:28 -04001057 Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
Vinh Trana3b8b782022-09-14 11:40:24 -04001058 },
Vinh Tran367d89d2023-04-28 11:21:25 -04001059 android.CommonAttributes{
1060 Name: aidlLibName,
Liz Kammer2b3f56e2023-03-23 11:51:49 -04001061 Tags: apexAvailableTags,
Vinh Trana3b8b782022-09-14 11:40:24 -04001062 },
Vinh Tran367d89d2023-04-28 11:21:25 -04001063 &aidlLibraryAttributes{
1064 Srcs: aidlFiles,
Vinh Trana3b8b782022-09-14 11:40:24 -04001065 },
1066 )
Vinh Tran367d89d2023-04-28 11:21:25 -04001067 aidlLibsFromSrcs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
Vinh Trana3b8b782022-09-14 11:40:24 -04001068 }
Vinh Tran9f6796a2022-08-16 13:10:31 -04001069 }
1070
Vinh Tran367d89d2023-04-28 11:21:25 -04001071 allAidlLibs := aidlLibs.Clone()
1072 allAidlLibs.Append(aidlLibsFromSrcs)
1073
1074 if !allAidlLibs.IsEmpty() {
1075 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
1076 // Since parent cc_library already has these dependencies, we can add them as implementation
1077 // deps so that they don't re-export
1078 implementationDeps := linkerAttrs.deps.Clone()
1079 implementationDeps.Append(linkerAttrs.implementationDeps)
1080 implementationDynamicDeps := linkerAttrs.dynamicDeps.Clone()
1081 implementationDynamicDeps.Append(linkerAttrs.implementationDynamicDeps)
1082
1083 sdkAttrs := bp2BuildParseSdkAttributes(m)
1084
Vinh Trane6842942023-04-28 11:21:25 -04001085 exportedIncludes := bp2BuildParseExportedIncludes(ctx, m, &compilerAttrs.includes)
1086 includeAttrs := includesAttributes{
1087 Export_includes: exportedIncludes.Includes,
1088 Export_absolute_includes: exportedIncludes.AbsoluteIncludes,
1089 Export_system_includes: exportedIncludes.SystemIncludes,
1090 Local_includes: compilerAttrs.localIncludes,
1091 Absolute_includes: compilerAttrs.absoluteIncludes,
1092 }
1093
Vinh Tran367d89d2023-04-28 11:21:25 -04001094 ctx.CreateBazelTargetModule(
1095 bazel.BazelTargetModuleProperties{
1096 Rule_class: "cc_aidl_library",
1097 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
1098 },
1099 android.CommonAttributes{Name: ccAidlLibrarylabel},
1100 &ccAidlLibraryAttributes{
1101 Deps: *allAidlLibs,
1102 Implementation_deps: *implementationDeps,
1103 Implementation_dynamic_deps: *implementationDynamicDeps,
1104 Tags: apexAvailableTags,
1105 sdkAttributes: sdkAttrs,
Vinh Trane6842942023-04-28 11:21:25 -04001106 includesAttributes: includeAttrs,
Vinh Tran367d89d2023-04-28 11:21:25 -04001107 },
1108 )
1109 label := &bazel.LabelAttribute{
1110 Value: &bazel.Label{
1111 Label: ":" + ccAidlLibrarylabel,
1112 },
1113 }
1114 return label
1115 }
1116
Vinh Trana3b8b782022-09-14 11:40:24 -04001117 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -04001118}
1119
Yu Liufc603162022-03-01 15:44:08 -08001120func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +00001121 return sdkAttributes{
1122 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -08001123 Min_sdk_version: module.Properties.Min_sdk_version,
1124 }
1125}
1126
1127type sdkAttributes struct {
1128 Sdk_version *string
1129 Min_sdk_version *string
1130}
1131
Jingwen Chen107c0de2021-04-09 10:43:12 +00001132// Convenience struct to hold all attributes parsed from linker properties.
1133type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -05001134 deps bazel.LabelListAttribute
1135 implementationDeps bazel.LabelListAttribute
1136 dynamicDeps bazel.LabelListAttribute
1137 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -07001138 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -05001139 wholeArchiveDeps bazel.LabelListAttribute
1140 implementationWholeArchiveDeps bazel.LabelListAttribute
1141 systemDynamicDeps bazel.LabelListAttribute
1142 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -04001143
Rupert Shuttleworth484aa252021-12-10 07:22:53 -05001144 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001145 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -04001146 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001147 stripKeepSymbols bazel.BoolAttribute
1148 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
1149 stripKeepSymbolsList bazel.StringListAttribute
1150 stripAll bazel.BoolAttribute
1151 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -04001152 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -04001153}
1154
Liz Kammer54309532021-12-14 12:21:22 -05001155var (
1156 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -04001157 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -05001158)
1159
Vinh Tran85fb07c2022-09-16 16:17:48 -04001160// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
1161// since all libs are already excluded by default
Liz Kammer748d7072023-01-25 12:07:43 -05001162func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, props *BaseLinkerProperties) {
1163 excludeSharedLibs := bazelLabelForSharedDeps(ctx, props.Target.Apex.Exclude_shared_libs)
1164 sharedExcludes := bazel.LabelList{Excludes: excludeSharedLibs.Includes}
1165 sharedExcludesLabelList := bazel.LabelListAttribute{}
1166 sharedExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, sharedExcludes)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001167
Liz Kammer748d7072023-01-25 12:07:43 -05001168 la.dynamicDeps.Append(sharedExcludesLabelList)
1169 la.implementationDynamicDeps.Append(sharedExcludesLabelList)
1170
1171 excludeStaticLibs := bazelLabelForStaticDeps(ctx, props.Target.Apex.Exclude_static_libs)
1172 staticExcludes := bazel.LabelList{Excludes: excludeStaticLibs.Includes}
1173 staticExcludesLabelList := bazel.LabelListAttribute{}
1174 staticExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, staticExcludes)
1175
1176 la.deps.Append(staticExcludesLabelList)
1177 la.implementationDeps.Append(staticExcludesLabelList)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001178}
1179
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001180func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, module *Module, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
1181 isBinary := module.Binary()
Liz Kammere6583482021-10-19 13:56:10 -04001182 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
1183 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -04001184
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001185 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -04001186 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
1187 if axis == bazel.NoConfigAxis {
1188 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
1189 if proptools.Bool(props.Use_version_lib) {
1190 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
1191 // remove from static libs so there is no duplicate dependency
1192 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
1193 // only add the dep if it is not in progress
1194 if !versionLibAlreadyInDeps {
Yu Liufe978fd2023-04-24 16:37:18 -07001195 wholeStaticLibs = append(wholeStaticLibs, versionLib)
Liz Kammerbaced712022-09-16 09:01:29 -04001196 }
1197 }
1198 }
1199
Liz Kammere6583482021-10-19 13:56:10 -04001200 // Excludes to parallel Soong:
1201 // 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 -04001202 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001203
Vinh Tran85fb07c2022-09-16 16:17:48 -04001204 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1205 ctx,
1206 !isBinary,
1207 staticLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001208 props.Exclude_static_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001209 props.Export_static_lib_headers,
1210 bazelLabelForStaticDepsExcludes,
1211 )
Liz Kammer7a210ac2021-09-22 15:52:58 -04001212
Liz Kammere6583482021-10-19 13:56:10 -04001213 headerLibs := android.FirstUniqueStrings(props.Header_libs)
1214 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -04001215
Liz Kammere6583482021-10-19 13:56:10 -04001216 (&hDeps.export).Append(staticDeps.export)
1217 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001218
Liz Kammere6583482021-10-19 13:56:10 -04001219 (&hDeps.implementation).Append(staticDeps.implementation)
1220 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -04001221
Liz Kammere6583482021-10-19 13:56:10 -04001222 systemSharedLibs := props.System_shared_libs
1223 // systemSharedLibs distinguishes between nil/empty list behavior:
1224 // nil -> use default values
1225 // empty list -> no values specified
1226 if len(systemSharedLibs) > 0 {
1227 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
1228 }
1229 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
1230
1231 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -05001232 excludeSharedLibs := props.Exclude_shared_libs
1233 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
1234 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
1235 })
1236 for _, el := range usedSystem {
1237 if la.usedSystemDynamicDepAsDynamicDep == nil {
1238 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
1239 }
1240 la.usedSystemDynamicDepAsDynamicDep[el] = true
1241 }
1242
Vinh Tran85fb07c2022-09-16 16:17:48 -04001243 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1244 ctx,
1245 !isBinary,
1246 sharedLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001247 props.Exclude_shared_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001248 props.Export_shared_lib_headers,
1249 bazelLabelForSharedDepsExcludes,
1250 )
Liz Kammere6583482021-10-19 13:56:10 -04001251 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
1252 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Liz Kammer748d7072023-01-25 12:07:43 -05001253 la.resolveTargetApexProp(ctx, props)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001254
Wei Li81852ca2022-07-27 00:22:06 -07001255 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
Yu Liu10174ff2023-02-21 12:05:26 -08001256 // If a dependency in la.implementationDynamicDeps or la.dynamicDeps has stubs, its
1257 // stub variant should be used when the dependency is linked in a APEX. The
1258 // dependencies in NoConfigAxis and OsConfigurationAxis/OsAndroid are grouped by
1259 // having stubs or not, so Bazel select() statement can be used to choose
1260 // source/stub variants of them.
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001261 apexAvailable := module.ApexAvailable()
Spandan Dasac693b22023-04-24 00:07:38 +00001262 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.export, &la.dynamicDeps, 0, false)
1263 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.implementation, &la.implementationDynamicDeps, 1, false)
1264 if len(systemSharedLibs) > 0 {
1265 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, bazelLabelForSharedDeps(ctx, systemSharedLibs), &la.systemDynamicDeps, 2, true)
1266 }
Wei Li81852ca2022-07-27 00:22:06 -07001267 }
Liz Kammere6583482021-10-19 13:56:10 -04001268
1269 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1270 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1271 }
1272
1273 if Bool(props.Allow_undefined_symbols) {
1274 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1275 }
1276
1277 var linkerFlags []string
1278 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001279 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001280 // binaries remove static flag if -shared is in the linker flags
1281 if isBinary && android.InList("-shared", linkerFlags) {
1282 axisFeatures = append(axisFeatures, "-static_flag")
1283 }
1284 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001285
Alex Márquez Pérez Muñíz Díaz Puras Thaureaux01ec55e2023-01-30 22:53:04 +00001286 if !props.libCrt() {
1287 axisFeatures = append(axisFeatures, "-use_libcrt")
1288 }
1289 if !props.crt() {
1290 axisFeatures = append(axisFeatures, "-link_crt")
1291 }
1292
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001293 // This must happen before the addition of flags for Version Script and
1294 // Dynamic List, as these flags must be split on spaces and those must not
1295 linkerFlags = parseCommandLineFlags(linkerFlags, filterOutClangUnknownCflags)
1296
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001297 additionalLinkerInputs := bazel.LabelList{}
Liz Kammere6583482021-10-19 13:56:10 -04001298 if props.Version_script != nil {
1299 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001300 additionalLinkerInputs.Add(&label)
Liz Kammere6583482021-10-19 13:56:10 -04001301 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
Trevor Radcliffef06dd912023-05-19 14:51:41 +00001302 axisFeatures = append(axisFeatures, "android_cfi_exports_map")
Liz Kammere6583482021-10-19 13:56:10 -04001303 }
Alix773adaa2022-04-27 17:49:34 +00001304
1305 if props.Dynamic_list != nil {
1306 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001307 additionalLinkerInputs.Add(&label)
Alix773adaa2022-04-27 17:49:34 +00001308 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1309 }
1310
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001311 la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
Spandan Dasfb04c412023-05-15 18:35:36 +00001312 if axis == bazel.OsConfigurationAxis && (config == bazel.OsDarwin || config == bazel.OsLinux || config == bazel.OsWindows) {
1313 linkerFlags = append(linkerFlags, props.Host_ldlibs...)
1314 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001315 la.linkopts.SetSelectValue(axis, config, linkerFlags)
Liz Kammere6583482021-10-19 13:56:10 -04001316
1317 if axisFeatures != nil {
1318 la.features.SetSelectValue(axis, config, axisFeatures)
1319 }
Cole Faust6b29f592022-08-09 09:50:56 -07001320
1321 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1322 if !runtimeDeps.IsEmpty() {
1323 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1324 }
Liz Kammere6583482021-10-19 13:56:10 -04001325}
1326
Spandan Das2518c022023-03-17 03:02:32 +00001327var (
1328 apiSurfaceModuleLibCurrentPackage = "@api_surfaces//" + android.ModuleLibApi.String() + "/current:"
1329)
1330
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001331func availableToSameApexes(a, b []string) bool {
1332 if len(a) == 0 && len(b) == 0 {
1333 return true
1334 }
1335 differ, _, _ := android.ListSetDifference(a, b)
1336 return !differ
1337}
1338
Spandan Das4242f102023-04-19 22:31:54 +00001339var (
Spandan Das9cad90f2023-05-04 17:15:44 +00001340 apiDomainConfigSettingKey = android.NewOnceKey("apiDomainConfigSettingKey")
1341 apiDomainConfigSettingLock sync.Mutex
Spandan Das4242f102023-04-19 22:31:54 +00001342)
1343
Spandan Das9cad90f2023-05-04 17:15:44 +00001344func getApiDomainConfigSettingMap(config android.Config) *map[string]bool {
1345 return config.Once(apiDomainConfigSettingKey, func() interface{} {
Spandan Das4242f102023-04-19 22:31:54 +00001346 return &map[string]bool{}
1347 }).(*map[string]bool)
1348}
1349
Spandan Das9cad90f2023-05-04 17:15:44 +00001350var (
1351 testApexNameToApiDomain = map[string]string{
1352 "test_broken_com.android.art": "com.android.art",
1353 }
1354)
1355
Spandan Dasa43ae132023-05-08 18:33:16 +00001356// GetApiDomain returns the canonical name of the apex. This is synonymous to the apex_name definition.
1357// https://cs.android.com/android/_/android/platform/build/soong/+/e3f0281b8897da1fe23b2f4f3a05f1dc87bcc902:apex/prebuilt.go;l=81-83;drc=2dc7244af985a6ad701b22f1271e606cabba527f;bpv=1;bpt=0
1358// For test apexes, it uses a naming convention heuristic to determine the api domain.
1359// TODO (b/281548611): Move this build/soong/android
1360func GetApiDomain(apexName string) string {
Spandan Das9cad90f2023-05-04 17:15:44 +00001361 if apiDomain, exists := testApexNameToApiDomain[apexName]; exists {
1362 return apiDomain
1363 }
1364 // Remove `test_` prefix
1365 return strings.TrimPrefix(apexName, "test_")
1366}
1367
Spandan Das4242f102023-04-19 22:31:54 +00001368// Create a config setting for this apex in build/bazel/rules/apex
1369// The use case for this is stub/impl selection in cc libraries
1370// Long term, these config_setting(s) should be colocated with the respective apex definitions.
1371// Note that this is an anti-pattern: The config_setting should be created from the apex definition
1372// and not from a cc_library.
1373// This anti-pattern is needed today since not all apexes have been allowlisted.
1374func createInApexConfigSetting(ctx android.TopDownMutatorContext, apexName string) {
1375 if apexName == android.AvailableToPlatform || apexName == android.AvailableToAnyApex {
1376 // These correspond to android-non_apex and android-in_apex
1377 return
1378 }
Spandan Das9cad90f2023-05-04 17:15:44 +00001379 apiDomainConfigSettingLock.Lock()
1380 defer apiDomainConfigSettingLock.Unlock()
Spandan Das4242f102023-04-19 22:31:54 +00001381
1382 // Return if a config_setting has already been created
Spandan Dasa43ae132023-05-08 18:33:16 +00001383 apiDomain := GetApiDomain(apexName)
Spandan Das9cad90f2023-05-04 17:15:44 +00001384 acsm := getApiDomainConfigSettingMap(ctx.Config())
1385 if _, exists := (*acsm)[apiDomain]; exists {
Spandan Das4242f102023-04-19 22:31:54 +00001386 return
1387 }
Spandan Das9cad90f2023-05-04 17:15:44 +00001388 (*acsm)[apiDomain] = true
Spandan Das4242f102023-04-19 22:31:54 +00001389
1390 csa := bazel.ConfigSettingAttributes{
1391 Flag_values: bazel.StringMapAttribute{
Spandan Das9cad90f2023-05-04 17:15:44 +00001392 "//build/bazel/rules/apex:api_domain": apiDomain,
Spandan Das4242f102023-04-19 22:31:54 +00001393 },
Spandan Das9cad90f2023-05-04 17:15:44 +00001394 // Constraint this to android
1395 Constraint_values: bazel.MakeLabelListAttribute(
1396 bazel.MakeLabelList(
1397 []bazel.Label{
1398 bazel.Label{Label: "//build/bazel/platforms/os:android"},
1399 },
1400 ),
1401 ),
Spandan Das4242f102023-04-19 22:31:54 +00001402 }
1403 ca := android.CommonAttributes{
Spandan Das9cad90f2023-05-04 17:15:44 +00001404 Name: apiDomain,
Spandan Das4242f102023-04-19 22:31:54 +00001405 }
1406 ctx.CreateBazelConfigSetting(
1407 csa,
1408 ca,
1409 "build/bazel/rules/apex",
1410 )
1411}
1412
1413func inApexConfigSetting(apexAvailable string) string {
1414 if apexAvailable == android.AvailableToPlatform {
Spandan Das6d4d9da2023-04-18 06:20:40 +00001415 return bazel.AndroidPlatform
Spandan Das4242f102023-04-19 22:31:54 +00001416 }
1417 if apexAvailable == android.AvailableToAnyApex {
1418 return bazel.AndroidAndInApex
1419 }
Spandan Dasa43ae132023-05-08 18:33:16 +00001420 apiDomain := GetApiDomain(apexAvailable)
Spandan Das9cad90f2023-05-04 17:15:44 +00001421 return "//build/bazel/rules/apex:" + apiDomain
Spandan Das4242f102023-04-19 22:31:54 +00001422}
1423
Spandan Das6d4d9da2023-04-18 06:20:40 +00001424// Inputs to stub vs impl selection.
1425type stubSelectionInfo struct {
1426 // Label of the implementation library (e.g. //bionic/libc:libc)
1427 impl bazel.Label
1428 // Axis containing the implementation library
1429 axis bazel.ConfigurationAxis
1430 // Axis key containing the implementation library
1431 config string
1432 // API domain of the apex
1433 // For test apexes (test_com.android.foo), this will be the source apex (com.android.foo)
1434 apiDomain string
1435 // List of dep labels
1436 dynamicDeps *bazel.LabelListAttribute
1437 // Boolean value for determining if the dep is in the same api domain
1438 // If false, the label will be rewritten to to the stub label
1439 sameApiDomain bool
1440}
1441
1442func useStubOrImplInApexWithName(ssi stubSelectionInfo) {
1443 lib := ssi.impl
1444 if !ssi.sameApiDomain {
1445 lib = bazel.Label{
1446 Label: apiSurfaceModuleLibCurrentPackage + strings.TrimPrefix(lib.OriginalModuleName, ":"),
1447 }
1448 }
1449 // Create a select statement specific to this apex
1450 inApexSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain))
1451 (&inApexSelectValue).Append(bazel.MakeLabelList([]bazel.Label{lib}))
1452 ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain), bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1453 // Delete the library from the common config for this apex
1454 implDynamicDeps := ssi.dynamicDeps.SelectValue(ssi.axis, ssi.config)
1455 implDynamicDeps = bazel.SubtractBazelLabelList(implDynamicDeps, bazel.MakeLabelList([]bazel.Label{ssi.impl}))
1456 ssi.dynamicDeps.SetSelectValue(ssi.axis, ssi.config, implDynamicDeps)
1457 if ssi.axis == bazel.NoConfigAxis {
1458 // Set defaults. Defaults (i.e. host) should use impl and not stubs.
1459 defaultSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
1460 (&defaultSelectValue).Append(bazel.MakeLabelList([]bazel.Label{ssi.impl}))
1461 ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
1462 }
Liz Kammere6583482021-10-19 13:56:10 -04001463}
1464
Yu Liu10174ff2023-02-21 12:05:26 -08001465func setStubsForDynamicDeps(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis,
Spandan Dasac693b22023-04-24 00:07:38 +00001466 config string, apexAvailable []string, dynamicLibs bazel.LabelList, dynamicDeps *bazel.LabelListAttribute, ind int, buildNonApexWithStubs bool) {
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001467
Spandan Das4242f102023-04-19 22:31:54 +00001468 // Create a config_setting for each apex_available.
1469 // This will be used to select impl of a dep if dep is available to the same apex.
1470 for _, aa := range apexAvailable {
1471 createInApexConfigSetting(ctx.(android.TopDownMutatorContext), aa)
1472 }
1473
Spandan Das6d4d9da2023-04-18 06:20:40 +00001474 apiDomainForSelects := []string{}
1475 for _, apex := range apexAvailable {
1476 apiDomainForSelects = append(apiDomainForSelects, GetApiDomain(apex))
1477 }
1478 // Always emit a select statement for the platform variant.
1479 // This ensures that b build //foo --config=android works
1480 // Soong always creates a platform variant even when the library might not be available to platform.
1481 if !android.InList(android.AvailableToPlatform, apiDomainForSelects) {
1482 apiDomainForSelects = append(apiDomainForSelects, android.AvailableToPlatform)
1483 }
1484 apiDomainForSelects = android.SortedUniqueStrings(apiDomainForSelects)
1485
1486 // Create a select for each apex this library could be included in.
1487 for _, l := range dynamicLibs.Includes {
1488 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
1489 if c, ok := dep.(*Module); !ok || !c.HasStubsVariants() {
1490 continue
1491 }
1492 // TODO (b/280339069): Decrease the verbosity of the generated BUILD files
1493 for _, apiDomain := range apiDomainForSelects {
1494 var sameApiDomain bool
1495 if apiDomain == android.AvailableToPlatform {
1496 // Platform variants in Soong use equality of apex_available for stub/impl selection.
1497 // https://cs.android.com/android/_/android/platform/build/soong/+/316b0158fe57ee7764235923e7c6f3d530da39c6:cc/cc.go;l=3393-3404;drc=176271a426496fa2688efe2b40d5c74340c63375;bpv=1;bpt=0
1498 // One of the factors behind this design choice is cc_test
1499 // Tests only have a platform variant, and using equality of apex_available ensures
1500 // that tests of an apex library gets its implementation and not stubs.
1501 // TODO (b/280343104): Discuss if we can drop this special handling for platform variants.
1502 sameApiDomain = availableToSameApexes(apexAvailable, dep.(*Module).ApexAvailable())
Spandan Das6aaab9d2023-05-04 17:27:30 +00001503 if linkable, ok := ctx.Module().(LinkableInterface); ok && linkable.Bootstrap() {
1504 sameApiDomain = true
1505 }
Spandan Das6d4d9da2023-04-18 06:20:40 +00001506 } else {
1507 sameApiDomain = android.InList(apiDomain, dep.(*Module).ApexAvailable())
1508 }
1509 ssi := stubSelectionInfo{
1510 impl: l,
1511 axis: axis,
1512 config: config,
1513 apiDomain: apiDomain,
1514 dynamicDeps: dynamicDeps,
1515 sameApiDomain: sameApiDomain,
1516 }
1517 useStubOrImplInApexWithName(ssi)
1518 }
1519 }
Yu Liu10174ff2023-02-21 12:05:26 -08001520}
1521
Jingwen Chen55bc8202021-11-02 06:40:51 +00001522func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001523 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1524 if stripProperties, ok := props.(*StripProperties); ok {
1525 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1526 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1527 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1528 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1529 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001530 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001531 })
Liz Kammere6583482021-10-19 13:56:10 -04001532}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001533
Jingwen Chen55bc8202021-11-02 06:40:51 +00001534func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001535
Liz Kammer47535c52021-06-02 16:02:22 -04001536 type productVarDep struct {
1537 // the name of the corresponding excludes field, if one exists
1538 excludesField string
1539 // reference to the bazel attribute that should be set for the given product variable config
1540 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001541
Jingwen Chen55bc8202021-11-02 06:40:51 +00001542 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001543 }
1544
Zi Wang0a8a1292022-08-30 06:27:01 +00001545 // an intermediate attribute that holds Header_libs info, and will be appended to
1546 // implementationDeps at the end, to solve the confliction that both header_libs
1547 // and static_libs use implementationDeps.
1548 var headerDeps bazel.LabelListAttribute
1549
Liz Kammer47535c52021-06-02 16:02:22 -04001550 productVarToDepFields := map[string]productVarDep{
1551 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001552 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1553 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1554 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001555 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001556 }
1557
Liz Kammer47535c52021-06-02 16:02:22 -04001558 for name, dep := range productVarToDepFields {
1559 props, exists := productVariableProps[name]
1560 excludeProps, excludesExists := productVariableProps[dep.excludesField]
Sasha Smundak39a301c2022-12-29 17:11:49 -08001561 // if neither an include nor excludes property exists, then skip it
Liz Kammer47535c52021-06-02 16:02:22 -04001562 if !exists && !excludesExists {
1563 continue
1564 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001565 // Collect all the configurations that an include or exclude property exists for.
1566 // We want to iterate all configurations rather than either the include or exclude because, for a
1567 // particular configuration, we may have either only an include or an exclude to handle.
Cole Faust150f9a52023-04-26 10:52:24 -07001568 productConfigProps := make(map[android.ProductConfigOrSoongConfigProperty]bool, len(props)+len(excludeProps))
Jingwen Chen25825ca2021-11-15 12:28:43 +00001569 for p := range props {
1570 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001571 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001572 for p := range excludeProps {
1573 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001574 }
1575
Jingwen Chen25825ca2021-11-15 12:28:43 +00001576 for productConfigProp := range productConfigProps {
1577 prop, includesExists := props[productConfigProp]
1578 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001579 var includes, excludes []string
1580 var ok bool
1581 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001582 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001583 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1584 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001585 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001586 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1587 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001588
Jingwen Chen58ff6802021-11-17 12:14:41 +00001589 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001590 dep.attribute.SetSelectValue(
1591 productConfigProp.ConfigurationAxis(),
1592 productConfigProp.SelectKey(),
1593 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1594 )
Liz Kammer47535c52021-06-02 16:02:22 -04001595 }
1596 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001597 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001598}
Liz Kammer47535c52021-06-02 16:02:22 -04001599
Liz Kammer54309532021-12-14 12:21:22 -05001600func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1601 // if system dynamic deps have the default value, any use of a system dynamic library used will
1602 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001603 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001604 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -08001605 toRemove := bazelLabelForSharedDeps(ctx, android.SortedKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001606 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001607 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1608 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001609 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001610 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1611 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001612
1613 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001614 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1615 for _, lib := range toRemove.Includes {
Spandan Das2518c022023-03-17 03:02:32 +00001616 stubLabelInApiSurfaces := bazel.Label{
1617 Label: apiSurfaceModuleLibCurrentPackage + lib.OriginalModuleName,
1618 }
1619 stubsToRemove = append(stubsToRemove, stubLabelInApiSurfaces)
Liz Kammer91487d42022-09-13 11:27:11 -04001620 }
Spandan Das6d4d9da2023-04-18 06:20:40 +00001621 // system libraries (e.g. libc, libm, libdl) belong the com.android.runtime api domain
1622 // dedupe the stubs of these libraries from the other api domains (platform, other_apexes...)
1623 for _, aa := range ctx.Module().(*Module).ApexAvailable() {
1624 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, inApexConfigSetting(aa), bazel.MakeLabelList(stubsToRemove))
1625 }
1626 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidPlatform, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001627 }
1628
Liz Kammere6583482021-10-19 13:56:10 -04001629 la.deps.ResolveExcludes()
1630 la.implementationDeps.ResolveExcludes()
1631 la.dynamicDeps.ResolveExcludes()
1632 la.implementationDynamicDeps.ResolveExcludes()
1633 la.wholeArchiveDeps.ResolveExcludes()
1634 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001635
Jingwen Chen91220d72021-03-24 02:18:33 -04001636}
1637
Jingwen Chened9c17d2021-04-13 07:14:55 +00001638// Relativize a list of root-relative paths with respect to the module's
1639// directory.
1640//
1641// include_dirs Soong prop are root-relative (b/183742505), but
1642// local_include_dirs, export_include_dirs and export_system_include_dirs are
1643// module dir relative. This function makes a list of paths entirely module dir
1644// relative.
1645//
1646// For the `include` attribute, Bazel wants the paths to be relative to the
1647// module.
1648func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001649 var relativePaths []string
1650 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001651 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1652 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1653 if err != nil {
1654 panic(err)
1655 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001656 relativePaths = append(relativePaths, relativePath)
1657 }
1658 return relativePaths
1659}
1660
Liz Kammer5fad5012021-09-09 14:08:21 -04001661// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1662// attributes.
1663type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001664 AbsoluteIncludes bazel.StringListAttribute
1665 Includes bazel.StringListAttribute
1666 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001667}
1668
Liz Kammer54549442022-05-11 13:55:06 -04001669func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001670 var exported BazelIncludes
1671 if includes != nil {
1672 exported = *includes
1673 } else {
1674 exported = BazelIncludes{}
1675 }
Zi Wang1cb11802022-12-09 16:08:54 -08001676
1677 // cc library Export_include_dirs and Export_system_include_dirs are marked
1678 // "variant_prepend" in struct tag, set their prepend property to true to make
1679 // sure bp2build generates correct result.
1680 exported.Includes.Prepend = true
1681 exported.SystemIncludes.Prepend = true
1682
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001683 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1684 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1685 if len(flagExporterProperties.Export_include_dirs) > 0 {
1686 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1687 }
1688 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1689 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 -04001690 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001691 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001692 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001693 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001694 exported.Includes.DeduplicateAxesFromBase()
1695 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001696
Liz Kammer5fad5012021-09-09 14:08:21 -04001697 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001698}
Chris Parsons953b3562021-09-20 15:14:39 -04001699
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001700func BazelLabelNameForStaticModule(baseLabel string) string {
1701 return baseLabel + "_bp2build_cc_library_static"
1702}
1703
Jingwen Chen55bc8202021-11-02 06:40:51 +00001704func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001705 label := android.BazelModuleLabel(ctx, m)
Sasha Smundak39a301c2022-12-29 17:11:49 -08001706 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001707 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001708 }
1709 return label
1710}
1711
Jingwen Chen55bc8202021-11-02 06:40:51 +00001712func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001713 // cc_library, at it's root name, propagates the shared library, which depends on the static
1714 // library.
1715 return android.BazelModuleLabel(ctx, m)
1716}
1717
Jingwen Chen55bc8202021-11-02 06:40:51 +00001718func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001719 label := bazelLabelForStaticModule(ctx, m)
1720 if aModule, ok := m.(android.Module); ok {
1721 if android.IsModulePrebuilt(aModule) {
1722 label += "_alwayslink"
1723 }
1724 }
1725 return label
1726}
1727
Liz Kammer084d6a92023-06-22 16:23:53 -04001728// Replaces //a/b/my_xsd_config with //a/b/my_xsd_config-cpp
1729func xsdConfigCppTarget(ctx android.BazelConversionPathContext, mod blueprint.Module) string {
1730 callback := func(xsd android.XsdConfigBp2buildTargets) string {
1731 return xsd.CppBp2buildTargetName()
1732 }
1733 return android.XsdConfigBp2buildTarget(ctx, mod, callback)
1734}
1735
1736func bazelLabelForXsdConfig(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
1737 return android.BazelLabelForModuleDepsWithFn(ctx, modules, xsdConfigCppTarget)
1738}
1739
Jingwen Chen55bc8202021-11-02 06:40:51 +00001740func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001741 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1742}
1743
Jingwen Chen55bc8202021-11-02 06:40:51 +00001744func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001745 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1746}
1747
Jingwen Chen55bc8202021-11-02 06:40:51 +00001748func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001749 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1750}
1751
Jingwen Chen55bc8202021-11-02 06:40:51 +00001752func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001753 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1754}
1755
Jingwen Chen55bc8202021-11-02 06:40:51 +00001756func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001757 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1758}
1759
Jingwen Chen55bc8202021-11-02 06:40:51 +00001760func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001761 // This is not elegant, but bp2build's shared library targets only propagate
1762 // their header information as part of the normal C++ provider.
1763 return bazelLabelForSharedDeps(ctx, modules)
1764}
1765
Zi Wang0a8a1292022-08-30 06:27:01 +00001766func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1767 // This is only used when product_variable header_libs is processed, to follow
1768 // the pattern of depResolutionFunc
1769 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1770}
1771
Jingwen Chen55bc8202021-11-02 06:40:51 +00001772func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001773 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1774}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001775
1776type binaryLinkerAttrs struct {
1777 Linkshared *bool
Spandan Das39ccf932023-05-26 18:03:39 +00001778 Stem bazel.StringAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001779 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001780}
1781
Jingwen Chen55bc8202021-11-02 06:40:51 +00001782func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001783 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001784 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1785 linkerProps := props.(*BinaryLinkerProperties)
1786 staticExecutable := linkerProps.Static_executable
1787 if axis == bazel.NoConfigAxis {
1788 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1789 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001790 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001791 } else if staticExecutable != nil {
1792 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1793 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1794 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001795 }
Spandan Das39ccf932023-05-26 18:03:39 +00001796 if stem := linkerProps.Stem; stem != nil {
1797 attrs.Stem.SetSelectValue(axis, config, stem)
1798 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001799 if suffix := linkerProps.Suffix; suffix != nil {
1800 attrs.Suffix.SetSelectValue(axis, config, suffix)
1801 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001802 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001803
1804 return attrs
1805}
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001806
1807func bp2buildSanitizerFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1808 sanitizerFeatures := bazel.StringListAttribute{}
1809 bp2BuildPropParseHelper(ctx, m, &SanitizeProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1810 var features []string
1811 if sanitizerProps, ok := props.(*SanitizeProperties); ok {
1812 if sanitizerProps.Sanitize.Integer_overflow != nil && *sanitizerProps.Sanitize.Integer_overflow {
1813 features = append(features, "ubsan_integer_overflow")
1814 }
1815 for _, sanitizer := range sanitizerProps.Sanitize.Misc_undefined {
1816 features = append(features, "ubsan_"+sanitizer)
1817 }
Trevor Radcliffeded095c2023-06-12 19:18:28 +00001818 blocklist := sanitizerProps.Sanitize.Blocklist
1819 if blocklist != nil {
1820 // Format the blocklist name to be used in a feature name
1821 blocklistFeatureSuffix := strings.Replace(strings.ToLower(*blocklist), ".", "_", -1)
1822 features = append(features, "ubsan_blocklist_"+blocklistFeatureSuffix)
1823 }
Trevor Radcliffe523c5c62023-06-16 20:15:45 +00001824 if sanitizerProps.Sanitize.Cfi != nil && !proptools.Bool(sanitizerProps.Sanitize.Cfi) {
1825 features = append(features, "-android_cfi")
1826 } else if proptools.Bool(sanitizerProps.Sanitize.Cfi) {
Trevor Radcliffe27669c02023-03-28 20:47:10 +00001827 features = append(features, "android_cfi")
1828 if proptools.Bool(sanitizerProps.Sanitize.Config.Cfi_assembly_support) {
1829 features = append(features, "android_cfi_assembly_support")
1830 }
1831 }
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001832 sanitizerFeatures.SetSelectValue(axis, config, features)
1833 }
1834 })
1835 return sanitizerFeatures
1836}
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +00001837
1838func bp2buildLtoFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1839 lto_feature_name := "android_thin_lto"
1840 ltoBoolFeatures := bazel.BoolAttribute{}
1841 bp2BuildPropParseHelper(ctx, m, &LTOProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1842 if ltoProps, ok := props.(*LTOProperties); ok {
1843 thinProp := ltoProps.Lto.Thin != nil && *ltoProps.Lto.Thin
1844 thinPropSetToFalse := ltoProps.Lto.Thin != nil && !*ltoProps.Lto.Thin
1845 neverProp := ltoProps.Lto.Never != nil && *ltoProps.Lto.Never
1846 if thinProp {
1847 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(true))
1848 return
1849 }
1850 if neverProp || thinPropSetToFalse {
1851 if thinProp {
1852 ctx.ModuleErrorf("lto.thin and lto.never are mutually exclusive but were specified together")
1853 } else {
1854 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(false))
1855 }
1856 return
1857 }
1858 }
1859 ltoBoolFeatures.SetSelectValue(axis, config, nil)
1860 })
1861
1862 props := m.GetArchVariantProperties(ctx, &LTOProperties{})
1863 ltoStringFeatures, err := ltoBoolFeatures.ToStringListAttribute(func(boolPtr *bool, axis bazel.ConfigurationAxis, config string) []string {
1864 if boolPtr == nil {
1865 return []string{}
1866 }
1867 if !*boolPtr {
1868 return []string{"-" + lto_feature_name}
1869 }
1870 features := []string{lto_feature_name}
1871 if ltoProps, ok := props[axis][config].(*LTOProperties); ok {
1872 if ltoProps.Whole_program_vtables != nil && *ltoProps.Whole_program_vtables {
1873 features = append(features, "android_thin_lto_whole_program_vtables")
1874 }
1875 }
1876 return features
1877 })
1878 if err != nil {
1879 ctx.ModuleErrorf("Error processing LTO attributes: %s", err)
1880 }
1881 return ltoStringFeatures
1882}
Trevor Radcliffea8b44162023-04-14 18:25:24 +00001883
1884func convertHiddenVisibilityToFeatureBase(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1885 visibilityHiddenFeature := bazel.StringListAttribute{}
1886 bp2BuildPropParseHelper(ctx, m, &BaseCompilerProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1887 if baseCompilerProps, ok := props.(*BaseCompilerProperties); ok {
1888 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, baseCompilerProps.Cflags)
1889 }
1890 })
1891 return visibilityHiddenFeature
1892}
1893
1894func convertHiddenVisibilityToFeatureStaticOrShared(ctx android.BazelConversionPathContext, m *Module, isStatic bool) bazel.StringListAttribute {
1895 visibilityHiddenFeature := bazel.StringListAttribute{}
1896 if isStatic {
1897 bp2BuildPropParseHelper(ctx, m, &StaticProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1898 if staticProps, ok := props.(*StaticProperties); ok {
1899 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, staticProps.Static.Cflags)
1900 }
1901 })
1902 } else {
1903 bp2BuildPropParseHelper(ctx, m, &SharedProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1904 if sharedProps, ok := props.(*SharedProperties); ok {
1905 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, sharedProps.Shared.Cflags)
1906 }
1907 })
1908 }
1909
1910 return visibilityHiddenFeature
1911}
1912
1913func convertHiddenVisibilityToFeatureHelper(feature *bazel.StringListAttribute, axis bazel.ConfigurationAxis, configString string, cflags []string) {
1914 if inList(config.VisibilityHiddenFlag, cflags) {
1915 feature.SetSelectValue(axis, configString, []string{"visibility_hidden"})
1916 }
1917}