blob: 9e485d6d07eca43f93fbb3058a268fcb478499b6 [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 Kammer0db0e342023-07-18 11:39:30 -040025 "android/soong/genrule"
Liz Kammer7a210ac2021-09-22 15:52:58 -040026
Chris Parsons953b3562021-09-20 15:14:39 -040027 "github.com/google/blueprint"
Liz Kammerba7a9c52021-05-26 08:45:30 -040028
29 "github.com/google/blueprint/proptools"
Jingwen Chen91220d72021-03-24 02:18:33 -040030)
31
Liz Kammerae3994e2021-10-19 09:45:48 -040032const (
Trevor Radcliffecee4e052022-09-06 19:31:25 +000033 cSrcPartition = "c"
34 asSrcPartition = "as"
35 asmSrcPartition = "asm"
36 lSrcPartition = "l"
37 llSrcPartition = "ll"
38 cppSrcPartition = "cpp"
39 protoSrcPartition = "proto"
40 aidlSrcPartition = "aidl"
41 syspropSrcPartition = "sysprop"
Alixe2667872023-04-24 14:57:32 +000042
43 yaccSrcPartition = "yacc"
44
45 rScriptSrcPartition = "renderScript"
Liz Kammer91487d42022-09-13 11:27:11 -040046
Liz Kammer5f5dbaa2023-07-17 17:44:08 -040047 xsdSrcPartition = "xsd"
48
Liz Kammer0db0e342023-07-18 11:39:30 -040049 genrulePartition = "genrule"
50
Liz Kammer5f5dbaa2023-07-17 17:44:08 -040051 hdrPartition = "hdr"
52
Liz Kammer91487d42022-09-13 11:27:11 -040053 stubsSuffix = "_stub_libs_current"
Liz Kammerae3994e2021-10-19 09:45:48 -040054)
55
Liz Kammer2222c6b2021-05-24 15:41:47 -040056// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000057// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040058type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040059 Srcs bazel.LabelListAttribute
60 Srcs_c bazel.LabelListAttribute
61 Srcs_as bazel.LabelListAttribute
62 Srcs_aidl bazel.LabelListAttribute
63 Hdrs bazel.LabelListAttribute
64 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000065
Liz Kammer12615db2021-09-28 09:19:17 -040066 Deps bazel.LabelListAttribute
67 Implementation_deps bazel.LabelListAttribute
68 Dynamic_deps bazel.LabelListAttribute
69 Implementation_dynamic_deps bazel.LabelListAttribute
70 Whole_archive_deps bazel.LabelListAttribute
71 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070072 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040073
74 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050075
76 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080077
Yu Liuf01a0f02022-12-07 15:45:30 -080078 Native_coverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -070079
Liz Kammeraceec252023-03-24 09:46:36 -040080 Apex_available []string
81
Trevor Radcliffea8b44162023-04-14 18:25:24 +000082 Features bazel.StringListAttribute
83
Yu Liufc603162022-03-01 15:44:08 -080084 sdkAttributes
Sam Delmericofb3bb322022-10-21 10:42:24 -040085
86 tidyAttributes
87}
88
89type tidyAttributes struct {
Sam Delmerico63f0c932023-03-14 14:05:28 -040090 Tidy *string
Sam Delmericofb3bb322022-10-21 10:42:24 -040091 Tidy_flags []string
92 Tidy_checks []string
93 Tidy_checks_as_errors []string
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040094 Tidy_disabled_srcs bazel.LabelListAttribute
Sam Delmerico4c902d62022-11-02 14:17:15 -040095 Tidy_timeout_srcs bazel.LabelListAttribute
Sam Delmericofb3bb322022-10-21 10:42:24 -040096}
97
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040098func (m *Module) convertTidyAttributes(ctx android.BaseMutatorContext, moduleAttrs *tidyAttributes) {
Sam Delmericofb3bb322022-10-21 10:42:24 -040099 for _, f := range m.features {
100 if tidy, ok := f.(*tidyFeature); ok {
Sam Delmerico63f0c932023-03-14 14:05:28 -0400101 var tidyAttr *string
102 if tidy.Properties.Tidy != nil {
103 if *tidy.Properties.Tidy {
104 tidyAttr = proptools.StringPtr("local")
105 } else {
106 tidyAttr = proptools.StringPtr("never")
107 }
108 }
109 moduleAttrs.Tidy = tidyAttr
Sam Delmericofb3bb322022-10-21 10:42:24 -0400110 moduleAttrs.Tidy_flags = tidy.Properties.Tidy_flags
111 moduleAttrs.Tidy_checks = tidy.Properties.Tidy_checks
112 moduleAttrs.Tidy_checks_as_errors = tidy.Properties.Tidy_checks_as_errors
113 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400114
115 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400116 archVariantProps := m.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
117 for axis, configToProps := range archVariantProps {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800118 for cfg, _props := range configToProps {
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400119 if archProps, ok := _props.(*BaseCompilerProperties); ok {
120 archDisabledSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_disabled_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800121 moduleAttrs.Tidy_disabled_srcs.SetSelectValue(axis, cfg, archDisabledSrcs)
Sam Delmerico4c902d62022-11-02 14:17:15 -0400122 archTimeoutSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_timeout_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800123 moduleAttrs.Tidy_timeout_srcs.SetSelectValue(axis, cfg, archTimeoutSrcs)
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400124 }
125 }
Sam Delmericofb3bb322022-10-21 10:42:24 -0400126 }
Jingwen Chen53681ef2021-04-29 08:15:13 +0000127}
128
Sam Delmericoc7681022022-02-04 21:01:20 +0000129// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000130func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400131 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
132 // macro.
133 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -0400134 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
135
136 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -0400137 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -0400138 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
139 return labelStr, false
140 }
Yu Liu2aa806b2022-09-01 11:54:47 -0700141 // If the filegroup is already converted to aidl_library or proto_library,
142 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
143 fg, _ := m.(android.FileGroupAsLibrary)
144 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -0400145 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000146 }
Liz Kammer12615db2021-09-28 09:19:17 -0400147 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400148 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000149 }
150
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400151 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +0000152 labels := bazel.LabelPartitions{
153 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500154 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
155 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -0700156 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -0400157 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000158 // TODO(http://b/231968910): If there is ever a filegroup target that
159 // contains .l or .ll files we will need to find a way to add a
160 // LabelMapper for these that identifies these filegroups and
161 // converts them appropriately
Alixe2667872023-04-24 14:57:32 +0000162 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
163 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
164 rScriptSrcPartition: bazel.LabelPartition{Extensions: []string{".fs", ".rscript"}},
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400165 xsdSrcPartition: bazel.LabelPartition{LabelMapper: android.XsdLabelMapper(xsdConfigCppTarget)},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400166 // C++ is the "catch-all" group, and comprises generated sources because we don't
167 // know the language of these sources until the genrule is executed.
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000168 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
169 syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
Spandan Dasdf4c2132023-05-09 23:58:52 +0000170 yaccSrcPartition: bazel.LabelPartition{Extensions: []string{".y", "yy"}},
Sam Delmericoc7681022022-02-04 21:01:20 +0000171 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000172
Sam Delmericoc7681022022-02-04 21:01:20 +0000173 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000174}
175
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400176func partitionHeaders(ctx android.BazelConversionPathContext, hdrs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
177 labels := bazel.LabelPartitions{
Liz Kammer0db0e342023-07-18 11:39:30 -0400178 xsdSrcPartition: bazel.LabelPartition{LabelMapper: android.XsdLabelMapper(xsdConfigCppTarget)},
179 genrulePartition: bazel.LabelPartition{LabelMapper: genrule.GenruleCcHeaderLabelMapper},
180 hdrPartition: bazel.LabelPartition{Keep_remainder: true},
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400181 }
182 return bazel.PartitionLabelListAttribute(ctx, &hdrs, labels)
183}
184
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000185// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000186func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000187 lib, ok := module.compiler.(*libraryDecorator)
188 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400189 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000190 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000191 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
192}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000193
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000194// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000195func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000196 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000197}
198
199// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000200func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000201 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400202}
203
Liz Kammer7a210ac2021-09-22 15:52:58 -0400204type depsPartition struct {
205 export bazel.LabelList
206 implementation bazel.LabelList
207}
208
Jingwen Chen55bc8202021-11-02 06:40:51 +0000209type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400210
Jingwen Chen55bc8202021-11-02 06:40:51 +0000211func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400212 if !exportsDeps {
213 return depsPartition{
214 implementation: fn(ctx, allDeps),
215 }
216 }
217
Liz Kammer7a210ac2021-09-22 15:52:58 -0400218 implementation, export := android.FilterList(allDeps, exportedDeps)
219
220 return depsPartition{
221 export: fn(ctx, export),
222 implementation: fn(ctx, implementation),
223 }
224}
225
Jingwen Chen55bc8202021-11-02 06:40:51 +0000226type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400227
Jingwen Chen55bc8202021-11-02 06:40:51 +0000228func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400229 if !exportsDeps {
230 return depsPartition{
231 implementation: fn(ctx, allDeps, excludes),
232 }
233 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400234 implementation, export := android.FilterList(allDeps, exportedDeps)
235
236 return depsPartition{
237 export: fn(ctx, export, excludes),
238 implementation: fn(ctx, implementation, excludes),
239 }
240}
241
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000242func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
243 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800244 for cfg, props := range configToProps {
245 parseFunc(axis, cfg, props)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000246 }
247 }
248}
249
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000250// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Liz Kammeraceec252023-03-24 09:46:36 -0400251func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400252 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000253
Liz Kammer9abd62d2021-05-21 08:37:59 -0400254 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000255 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutHiddenVisibility))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000256 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400257 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400258
Liz Kammer2b8004b2021-10-04 13:55:44 -0400259 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400260 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
261 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
262
Liz Kammer2b8004b2021-10-04 13:55:44 -0400263 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400264 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
265 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
266
267 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500268 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000269 }
Liz Kammer135bf552021-08-11 10:46:06 -0400270 // system_dynamic_deps distinguishes between nil/empty list behavior:
271 // nil -> use default values
272 // empty list -> no values specified
273 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000274
Liz Kammeraceec252023-03-24 09:46:36 -0400275 var apexAvailable []string
Jingwen Chenbcf53042021-05-26 04:42:42 +0000276 if isStatic {
Liz Kammeraceec252023-03-24 09:46:36 -0400277 apexAvailable = lib.StaticProperties.Static.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000278 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
279 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
280 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000281 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000282 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000283 } else {
Liz Kammeraceec252023-03-24 09:46:36 -0400284 apexAvailable = lib.SharedProperties.Shared.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000285 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
286 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
287 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000288 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000289 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000290 }
291
Liz Kammerae3994e2021-10-19 09:45:48 -0400292 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
293 attrs.Srcs = partitionedSrcs[cppSrcPartition]
294 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
295 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000296
Spandan Das39b6cc52023-04-12 19:05:49 +0000297 attrs.Apex_available = android.ConvertApexAvailableToTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), apexAvailable)
Liz Kammeraceec252023-03-24 09:46:36 -0400298
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000299 attrs.Features.Append(convertHiddenVisibilityToFeatureStaticOrShared(ctx, module, isStatic))
300
Liz Kammer12615db2021-09-28 09:19:17 -0400301 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
302 // TODO(b/208815215): determine whether this is used and add support if necessary
303 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
304 }
305
Jingwen Chenbcf53042021-05-26 04:42:42 +0000306 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000307}
308
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400309// Convenience struct to hold all attributes parsed from prebuilt properties.
310type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000311 Src bazel.LabelAttribute
312 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400313}
314
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000315func parseSrc(ctx android.BazelConversionPathContext, srcLabelAttribute *bazel.LabelAttribute, axis bazel.ConfigurationAxis, config string, srcs []string) {
316 srcFileError := func() {
317 ctx.ModuleErrorf("parseSrc: Expected at most one source file for %s %s\n", axis, config)
318 }
319 if len(srcs) > 1 {
320 srcFileError()
321 return
322 } else if len(srcs) == 0 {
323 return
324 }
325 if srcLabelAttribute.SelectValue(axis, config) != nil {
326 srcFileError()
327 return
328 }
329 srcLabelAttribute.SetSelectValue(axis, config, android.BazelLabelForModuleSrcSingle(ctx, srcs[0]))
330}
331
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000332// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000333func 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 +0000334
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400335 var srcLabelAttribute bazel.LabelAttribute
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000336 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
337 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000338 parseSrc(ctx, &srcLabelAttribute, axis, config, prebuiltLinkerProperties.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000339 }
340 })
341
342 var enabledLabelAttribute bazel.BoolAttribute
343 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
344 if props.Enabled != nil {
345 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
346 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000347 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000348 }
349
350 if isStatic {
351 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
352 if staticProperties, ok := props.(*StaticProperties); ok {
353 parseAttrs(axis, config, staticProperties.Static)
354 }
355 })
356 } else {
357 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
358 if sharedProperties, ok := props.(*SharedProperties); ok {
359 parseAttrs(axis, config, sharedProperties.Shared)
360 }
361 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400362 }
363
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400364 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000365 Src: srcLabelAttribute,
366 Enabled: enabledLabelAttribute,
367 }
368}
369
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000370func bp2BuildParsePrebuiltBinaryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
371 var srcLabelAttribute bazel.LabelAttribute
372 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
373 if props, ok := props.(*prebuiltLinkerProperties); ok {
374 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000375 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000376 })
377
378 return prebuiltAttributes{
379 Src: srcLabelAttribute,
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400380 }
381}
382
Colin Crossc5075e92022-12-05 16:46:39 -0800383func bp2BuildParsePrebuiltObjectProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
384 var srcLabelAttribute bazel.LabelAttribute
385 bp2BuildPropParseHelper(ctx, module, &prebuiltObjectProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
386 if props, ok := props.(*prebuiltObjectProperties); ok {
387 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
388 }
389 })
390
391 return prebuiltAttributes{
392 Src: srcLabelAttribute,
393 }
394}
395
Liz Kammere6583482021-10-19 13:56:10 -0400396type baseAttributes struct {
397 compilerAttributes
398 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400399
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000400 // A combination of compilerAttributes.features and linkerAttributes.features, as well as sanitizer features
Cole Faust5fa4e962022-08-22 14:31:04 -0700401 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400402 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400403 aidlDependency *bazel.LabelAttribute
Yu Liuf01a0f02022-12-07 15:45:30 -0800404 Native_coverage *bool
Liz Kammere6583482021-10-19 13:56:10 -0400405}
406
Jingwen Chen107c0de2021-04-09 10:43:12 +0000407// Convenience struct to hold all attributes parsed from compiler properties.
408type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400409 // Options for all languages
410 copts bazel.StringListAttribute
411 // Assembly options and sources
412 asFlags bazel.StringListAttribute
413 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700414 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400415 // C options and sources
416 conlyFlags bazel.StringListAttribute
417 cSrcs bazel.LabelListAttribute
418 // C++ options and sources
419 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000420 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400421
Liz Kammer084d6a92023-06-22 16:23:53 -0400422 // xsd config sources
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400423 xsdSrcs bazel.LabelListAttribute
424 exportXsdSrcs bazel.LabelListAttribute
Liz Kammer084d6a92023-06-22 16:23:53 -0400425
Liz Kammer0db0e342023-07-18 11:39:30 -0400426 // genrule headers
427 genruleHeaders bazel.LabelListAttribute
428 exportGenruleHeaders bazel.LabelListAttribute
429
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000430 // Lex sources and options
431 lSrcs bazel.LabelListAttribute
432 llSrcs bazel.LabelListAttribute
433 lexopts bazel.StringListAttribute
434
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000435 // Sysprop sources
436 syspropSrcs bazel.LabelListAttribute
437
Spandan Dasdf4c2132023-05-09 23:58:52 +0000438 // Yacc sources
439 yaccSrc *bazel.LabelAttribute
440 yaccFlags bazel.StringListAttribute
441 yaccGenLocationHeader bazel.BoolAttribute
442 yaccGenPositionHeader bazel.BoolAttribute
443
Alixe2667872023-04-24 14:57:32 +0000444 rsSrcs bazel.LabelListAttribute
445
Liz Kammere6583482021-10-19 13:56:10 -0400446 hdrs bazel.LabelListAttribute
447
Chris Parsons2c788392021-08-10 11:58:07 -0400448 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000449
450 // Not affected by arch variants
451 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500452 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000453 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400454
455 localIncludes bazel.StringListAttribute
456 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400457
Liz Kammer1263d9b2021-12-10 14:28:20 -0500458 includes BazelIncludes
459
Alixe2667872023-04-24 14:57:32 +0000460 protoSrcs bazel.LabelListAttribute
461 aidlSrcs bazel.LabelListAttribute
462 rscriptSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000463
464 stubsSymbolFile *string
465 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700466
467 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500468
Spandan Das39ccf932023-05-26 18:03:39 +0000469 stem bazel.StringAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500470 suffix bazel.StringAttribute
Vinh Tran99270ea2022-11-28 11:15:23 -0500471
472 fdoProfile bazel.LabelAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000473}
474
Liz Kammercac7f692021-12-16 14:19:32 -0500475type filterOutFn func(string) bool
476
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000477// filterOutHiddenVisibility removes the flag specifying hidden visibility as
478// this flag is converted to a toolchain feature
479func filterOutHiddenVisibility(flag string) bool {
480 return flag == config.VisibilityHiddenFlag
481}
482
Liz Kammercac7f692021-12-16 14:19:32 -0500483func filterOutStdFlag(flag string) bool {
484 return strings.HasPrefix(flag, "-std=")
485}
486
Alix1be00d42022-05-16 22:56:04 +0000487func filterOutClangUnknownCflags(flag string) bool {
488 for _, f := range config.ClangUnknownCflags {
489 if f == flag {
490 return true
491 }
492 }
493 return false
494}
495
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000496func parseCommandLineFlags(soongFlags []string, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400497 var result []string
498 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000499 skipFlag := false
500 for _, filter := range filterOut {
501 if filter != nil && filter(flag) {
502 skipFlag = true
503 }
504 }
505 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500506 continue
507 }
Liz Kammere6583482021-10-19 13:56:10 -0400508 // Soong's cflags can contain spaces, like `-include header.h`. For
509 // Bazel's copts, split them up to be compatible with the
510 // no_copts_tokenization feature.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000511 result = append(result, strings.Split(flag, " ")...)
Liz Kammere6583482021-10-19 13:56:10 -0400512 }
513 return result
514}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000515
Jingwen Chen55bc8202021-11-02 06:40:51 +0000516func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400517 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
518 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400519 srcsList, ok := parseSrcs(ctx, props)
Liz Kammer084d6a92023-06-22 16:23:53 -0400520
521 if ok {
Liz Kammere6583482021-10-19 13:56:10 -0400522 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400523 }
524
Liz Kammere6583482021-10-19 13:56:10 -0400525 localIncludeDirs := props.Local_include_dirs
526 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500527 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400528 if includeBuildDirectory(props.Include_build_directory) {
529 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400530 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000531 }
532
Liz Kammere6583482021-10-19 13:56:10 -0400533 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
534 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
535
Cole Faust5fa4e962022-08-22 14:31:04 -0700536 instructionSet := proptools.StringDefault(props.Instruction_set, "")
537 if instructionSet == "arm" {
Trevor Radcliffe5f0c2ac2023-05-15 18:00:59 +0000538 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm"})
Cole Faust5fa4e962022-08-22 14:31:04 -0700539 } else if instructionSet != "" && instructionSet != "thumb" {
540 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
541 }
542
Liz Kammercac7f692021-12-16 14:19:32 -0500543 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
544 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
545 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
546 // cases.
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000547 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutClangUnknownCflags, filterOutHiddenVisibility))
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000548 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
549 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, filterOutClangUnknownCflags))
550 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400551 ca.rtti.SetSelectValue(axis, config, props.Rtti)
552}
553
Jingwen Chen55bc8202021-11-02 06:40:51 +0000554func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000555 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
556 if stlProps, ok := props.(*StlProperties); ok {
557 if stlProps.Stl == nil {
558 return
559 }
560 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400561 stl := deduplicateStlInput(*stlProps.Stl)
562 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000563 } else if ca.stl != stlProps.Stl {
564 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 -0400565 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000566 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000567 })
Liz Kammere6583482021-10-19 13:56:10 -0400568}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000569
Jingwen Chen55bc8202021-11-02 06:40:51 +0000570func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400571 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400572 "Cflags": &ca.copts,
573 "Asflags": &ca.asFlags,
Yu Liu93893ba2023-05-01 13:49:52 -0700574 "Cppflags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400575 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400576 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000577 if productConfigProps, exists := productVariableProps[propName]; exists {
578 for productConfigProp, prop := range productConfigProps {
579 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400580 if !ok {
581 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
582 }
Cole Faust150f9a52023-04-26 10:52:24 -0700583 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name())
Jingwen Chen25825ca2021-11-15 12:28:43 +0000584 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400585 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400586 }
587 }
Liz Kammere6583482021-10-19 13:56:10 -0400588}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400589
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400590func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs, exportHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400591 ca.srcs.ResolveExcludes()
592 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400593 partitionedImplHdrs := partitionHeaders(ctx, implementationHdrs)
594 partitionedHdrs := partitionHeaders(ctx, exportHdrs)
Liz Kammere6583482021-10-19 13:56:10 -0400595
Liz Kammer12615db2021-09-28 09:19:17 -0400596 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Vinh Tran9f6796a2022-08-16 13:10:31 -0400597 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400598
Liz Kammere6583482021-10-19 13:56:10 -0400599 for p, lla := range partitionedSrcs {
600 // if there are no sources, there is no need for headers
601 if lla.IsEmpty() {
602 continue
603 }
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400604 lla.Append(partitionedImplHdrs[hdrPartition])
Liz Kammere6583482021-10-19 13:56:10 -0400605 partitionedSrcs[p] = lla
606 }
607
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400608 ca.hdrs = partitionedHdrs[hdrPartition]
609
610 ca.includesFromHeaders(ctx, partitionedImplHdrs[hdrPartition], partitionedHdrs[hdrPartition])
611
612 xsdSrcs := bazel.SubtractBazelLabelListAttribute(partitionedSrcs[xsdSrcPartition], partitionedHdrs[xsdSrcPartition])
613 xsdSrcs.Append(partitionedImplHdrs[xsdSrcPartition])
614 ca.exportXsdSrcs = partitionedHdrs[xsdSrcPartition]
615 ca.xsdSrcs = bazel.FirstUniqueBazelLabelListAttribute(xsdSrcs)
616
Liz Kammer0db0e342023-07-18 11:39:30 -0400617 ca.genruleHeaders = partitionedImplHdrs[genrulePartition]
618 ca.exportGenruleHeaders = partitionedHdrs[genrulePartition]
619
Liz Kammere6583482021-10-19 13:56:10 -0400620 ca.srcs = partitionedSrcs[cppSrcPartition]
621 ca.cSrcs = partitionedSrcs[cSrcPartition]
622 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700623 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000624 ca.lSrcs = partitionedSrcs[lSrcPartition]
625 ca.llSrcs = partitionedSrcs[llSrcPartition]
Spandan Dasdf4c2132023-05-09 23:58:52 +0000626 if yacc := partitionedSrcs[yaccSrcPartition]; !yacc.IsEmpty() {
627 if len(yacc.Value.Includes) > 1 {
628 ctx.PropertyErrorf("srcs", "Found multiple yacc (.y/.yy) files in library")
629 }
630 ca.yaccSrc = bazel.MakeLabelAttribute(yacc.Value.Includes[0].Label)
631 }
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000632 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
Alixe2667872023-04-24 14:57:32 +0000633 ca.rscriptSrcs = partitionedSrcs[rScriptSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400634
635 ca.absoluteIncludes.DeduplicateAxesFromBase()
636 ca.localIncludes.DeduplicateAxesFromBase()
637}
638
639// Parse srcs from an arch or OS's props value.
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400640func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400641 anySrcs := false
642 // Add srcs-like dependencies such as generated files.
643 // First create a LabelList containing these dependencies, then merge the values with srcs.
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400644 genSrcs := props.Generated_sources
Spandan Das922171d2023-05-31 23:32:40 +0000645 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, genSrcs, props.Exclude_generated_sources)
Liz Kammere6583482021-10-19 13:56:10 -0400646 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
647 anySrcs = true
648 }
649
650 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400651
Liz Kammere6583482021-10-19 13:56:10 -0400652 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
653 anySrcs = true
654 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400655
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400656 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
Liz Kammere6583482021-10-19 13:56:10 -0400657}
658
Liz Kammera5a29de2022-05-25 23:19:37 -0400659func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
660 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500661 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
662 // Defaults are handled by the toolchain definition.
663 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400664 stdVal := proptools.StringDefault(std, defaultVal)
665 if stdVal == "experimental" || stdVal == defaultVal {
666 if stdVal == "experimental" {
667 stdVal = prefix + "_std_experimental"
668 }
669 if !useGnu {
670 stdVal += "_no_gnu"
671 }
672 } else if !useGnu {
673 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500674 }
675
Liz Kammera5a29de2022-05-25 23:19:37 -0400676 if stdVal == defaultVal {
677 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500678 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400679 return &stdVal
680}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500681
Liz Kammera5a29de2022-05-25 23:19:37 -0400682func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
683 useGnu := useGnuExtensions(gnu_extensions)
684
685 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400686}
687
Liz Kammer1263d9b2021-12-10 14:28:20 -0500688// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
689// is fully-qualified.
690// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
691func packageFromLabel(label string) (string, bool) {
692 split := strings.Split(label, ":")
693 if len(split) != 2 {
694 return "", false
695 }
696 if split[0] == "" {
697 return ".", false
698 }
699 // remove leading "//"
700 return split[0][2:], true
701}
702
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400703// includesFromHeaders gets the include directories needed from generated headers
704func (ca *compilerAttributes) includesFromHeaders(ctx android.BazelConversionPathContext, implHdrs, hdrs bazel.LabelListAttribute) {
705 local, absolute := includesFromLabelListAttribute(implHdrs, ca.localIncludes, ca.absoluteIncludes)
706 localExport, absoluteExport := includesFromLabelListAttribute(hdrs, ca.includes.Includes, ca.includes.AbsoluteIncludes)
707
708 ca.localIncludes = local
709 ca.absoluteIncludes = absolute
710
711 ca.includes.Includes = localExport
712 ca.includes.AbsoluteIncludes = absoluteExport
713}
714
715// includesFromLabelList extracts the packages from a LabelListAttribute that should be includes and
716// combines them with existing local/absolute includes.
717func includesFromLabelListAttribute(attr bazel.LabelListAttribute, existingLocal, existingAbsolute bazel.StringListAttribute) (bazel.StringListAttribute, bazel.StringListAttribute) {
718 localAttr := existingLocal.Clone()
719 absoluteAttr := existingAbsolute.Clone()
720 if !attr.Value.IsEmpty() {
721 l, a := includesFromLabelList(attr.Value, existingLocal.Value, existingAbsolute.Value)
722 localAttr.SetSelectValue(bazel.NoConfigAxis, "", l)
723 absoluteAttr.SetSelectValue(bazel.NoConfigAxis, "", a)
724 }
725 for axis, configToLabels := range attr.ConfigurableValues {
726 for c, labels := range configToLabels {
727 local := existingLocal.SelectValue(axis, c)
728 absolute := existingAbsolute.SelectValue(axis, c)
729 l, a := includesFromLabelList(labels, local, absolute)
730 localAttr.SetSelectValue(axis, c, l)
731 absoluteAttr.SetSelectValue(axis, c, a)
732 }
733 }
734 return *localAttr, *absoluteAttr
735}
736
737// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList.
738func includesFromLabelList(labelList bazel.LabelList, existingRel, existingAbs []string) ([]string, []string) {
739 var relative, absolute []string
Liz Kammer1263d9b2021-12-10 14:28:20 -0500740 for _, hdr := range labelList.Includes {
741 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
742 absolute = append(absolute, pkg)
743 } else if pkg != "" {
744 relative = append(relative, pkg)
745 }
746 }
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400747 if len(relative)+len(existingRel) != 0 {
748 relative = android.FirstUniqueStrings(append(append([]string{}, existingRel...), relative...))
749 }
750 if len(absolute)+len(existingAbs) != 0 {
751 absolute = android.FirstUniqueStrings(append(append([]string{}, existingAbs...), absolute...))
752 }
Liz Kammer1263d9b2021-12-10 14:28:20 -0500753 return relative, absolute
754}
755
Cole Faust7071a052022-07-29 15:58:33 -0700756type YasmAttributes struct {
757 Srcs bazel.LabelListAttribute
758 Flags bazel.StringListAttribute
759 Include_dirs bazel.StringListAttribute
760}
761
762func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
763 if ca.asmSrcs.IsEmpty() {
764 return nil
765 }
766
767 // Yasm needs the include directories from both local_includes and
768 // export_include_dirs. We don't care about actually exporting them from the
769 // yasm rule though, because they will also be present on the cc_ rule that
770 // wraps this yasm rule.
771 includes := ca.localIncludes.Clone()
772 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
773 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
774 if len(flagExporterProperties.Export_include_dirs) > 0 {
775 x := bazel.StringListAttribute{}
776 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
777 includes.Append(x)
778 }
779 }
780 })
781
782 ctx.CreateBazelTargetModule(
783 bazel.BazelTargetModuleProperties{
784 Rule_class: "yasm",
785 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
786 },
787 android.CommonAttributes{Name: m.Name() + "_yasm"},
788 &YasmAttributes{
789 Srcs: ca.asmSrcs,
790 Flags: ca.asFlags,
791 Include_dirs: *includes,
792 })
793
794 // We only want to add a dependency on the _yasm target if there are asm
795 // sources in the current configuration. If there are unconfigured asm
796 // sources, always add the dependency. Otherwise, add the dependency only
797 // on the configuration axes and values that had asm sources.
798 if len(ca.asmSrcs.Value.Includes) > 0 {
799 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
800 }
801
802 ret := &bazel.LabelAttribute{}
803 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800804 for cfg := range ca.asmSrcs.ConfigurableValues[axis] {
805 ret.SetSelectValue(axis, cfg, bazel.Label{Label: ":" + m.Name() + "_yasm"})
Cole Faust7071a052022-07-29 15:58:33 -0700806 }
807 }
808 return ret
809}
810
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000811// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400812func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400813 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
814 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000815 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400816
Liz Kammere6583482021-10-19 13:56:10 -0400817 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
818 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
819 for axis, configMap := range cp {
820 if _, ok := axisToConfigs[axis]; !ok {
821 axisToConfigs[axis] = map[string]bool{}
822 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800823 for cfg := range configMap {
824 axisToConfigs[axis][cfg] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400825 }
826 }
827 }
Liz Kammere6583482021-10-19 13:56:10 -0400828 allAxesAndConfigs(archVariantCompilerProps)
829 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000830 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400831
Liz Kammere6583482021-10-19 13:56:10 -0400832 compilerAttrs := compilerAttributes{}
833 linkerAttrs := linkerAttributes{}
834
Vinh Tran367d89d2023-04-28 11:21:25 -0400835 var aidlLibs bazel.LabelList
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400836 var implementationHdrs, exportHdrs bazel.LabelListAttribute
Vinh Tran367d89d2023-04-28 11:21:25 -0400837
Chris Parsons7b3289b2023-01-26 17:30:44 -0500838 // Iterate through these axes in a deterministic order. This is required
839 // because processing certain dependencies may result in concatenating
840 // elements along other axes. (For example, processing NoConfig may result
841 // in elements being added to InApex). This is thus the only way to ensure
842 // that the order of entries in each list is in a predictable order.
843 for _, axis := range bazel.SortedConfigurationAxes(axisToConfigs) {
844 configs := axisToConfigs[axis]
Sasha Smundak39a301c2022-12-29 17:11:49 -0800845 for cfg := range configs {
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400846 var allHdrs []string
Sasha Smundak39a301c2022-12-29 17:11:49 -0800847 if baseCompilerProps, ok := archVariantCompilerProps[axis][cfg].(*BaseCompilerProperties); ok {
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400848 allHdrs = baseCompilerProps.Generated_headers
Spandan Das922171d2023-05-31 23:32:40 +0000849
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000850 if baseCompilerProps.Lex != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800851 compilerAttrs.lexopts.SetSelectValue(axis, cfg, baseCompilerProps.Lex.Flags)
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000852 }
Spandan Dasdf4c2132023-05-09 23:58:52 +0000853 if baseCompilerProps.Yacc != nil {
854 compilerAttrs.yaccFlags.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Flags)
855 compilerAttrs.yaccGenLocationHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_location_hh)
856 compilerAttrs.yaccGenPositionHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_position_hh)
857 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800858 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, cfg, baseCompilerProps)
Vinh Tran367d89d2023-04-28 11:21:25 -0400859 aidlLibs.Append(android.BazelLabelForModuleDeps(ctx, baseCompilerProps.Aidl.Libs))
Liz Kammere6583482021-10-19 13:56:10 -0400860 }
861
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400862 var exportedHdrs []string
Liz Kammere6583482021-10-19 13:56:10 -0400863
Sasha Smundak39a301c2022-12-29 17:11:49 -0800864 if baseLinkerProps, ok := archVariantLinkerProps[axis][cfg].(*BaseLinkerProperties); ok {
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400865 exportedHdrs = baseLinkerProps.Export_generated_headers
Liz Kammer48cdbeb2023-03-17 10:17:50 -0400866 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module, axis, cfg, baseLinkerProps)
Liz Kammere6583482021-10-19 13:56:10 -0400867 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400868
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400869 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportedHdrs, android.BazelLabelForModuleDeps)
Liz Kammer084d6a92023-06-22 16:23:53 -0400870
Sasha Smundak39a301c2022-12-29 17:11:49 -0800871 implementationHdrs.SetSelectValue(axis, cfg, headers.implementation)
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400872 exportHdrs.SetSelectValue(axis, cfg, headers.export)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000873
Sasha Smundak39a301c2022-12-29 17:11:49 -0800874 if libraryProps, ok := archVariantLibraryProperties[axis][cfg].(*LibraryProperties); ok {
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000875 if axis == bazel.NoConfigAxis {
Sam Delmerico75dbca22023-04-20 13:13:25 +0000876 if libraryProps.Stubs.Symbol_file != nil {
877 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
878 versions := android.CopyOf(libraryProps.Stubs.Versions)
879 normalizeVersions(ctx, versions)
880 versions = addCurrentVersionIfNotPresent(versions)
881 compilerAttrs.stubsVersions.SetSelectValue(axis, cfg, versions)
882 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000883 }
Spandan Das39ccf932023-05-26 18:03:39 +0000884 if stem := libraryProps.Stem; stem != nil {
885 compilerAttrs.stem.SetSelectValue(axis, cfg, stem)
886 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500887 if suffix := libraryProps.Suffix; suffix != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800888 compilerAttrs.suffix.SetSelectValue(axis, cfg, suffix)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500889 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000890 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400891
Liz Kammere6583482021-10-19 13:56:10 -0400892 }
893 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400894
Liz Kammere6583482021-10-19 13:56:10 -0400895 compilerAttrs.convertStlProps(ctx, module)
896 (&linkerAttrs).convertStripProps(ctx, module)
897
Yu Liuf01a0f02022-12-07 15:45:30 -0800898 var nativeCoverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -0700899 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
900 !Bool(module.coverage.Properties.Native_coverage) {
Yu Liuf01a0f02022-12-07 15:45:30 -0800901 nativeCoverage = BoolPtr(false)
Yu Liu8d82ac52022-05-17 15:13:28 -0700902 }
903
Cole Faust912bc882023-03-08 12:29:50 -0800904 productVariableProps := android.ProductVariableProperties(ctx, ctx.Module())
Liz Kammere6583482021-10-19 13:56:10 -0400905
906 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
907 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
908
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400909 (&compilerAttrs).finalize(ctx, implementationHdrs, exportHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500910 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400911
Cole Faust7071a052022-07-29 15:58:33 -0700912 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
913
Liz Kammer0db0e342023-07-18 11:39:30 -0400914 (&linkerAttrs).deps.Append(compilerAttrs.exportGenruleHeaders)
915 (&linkerAttrs).implementationDeps.Append(compilerAttrs.genruleHeaders)
916
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400917 (&linkerAttrs).wholeArchiveDeps.Append(compilerAttrs.exportXsdSrcs)
918 (&linkerAttrs).implementationWholeArchiveDeps.Append(compilerAttrs.xsdSrcs)
919
Liz Kammer12615db2021-09-28 09:19:17 -0400920 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
921
922 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
923 // which. This will add the newly generated proto library to the appropriate attribute and nothing
924 // to the other
925 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
926 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400927
Vinh Tran367d89d2023-04-28 11:21:25 -0400928 aidlDep := bp2buildCcAidlLibrary(
929 ctx, module,
930 compilerAttrs.aidlSrcs,
931 bazel.LabelListAttribute{
932 Value: aidlLibs,
933 },
934 linkerAttrs,
Vinh Trane6842942023-04-28 11:21:25 -0400935 compilerAttrs,
Vinh Tran367d89d2023-04-28 11:21:25 -0400936 )
Vinh Tranfde57eb2022-08-29 17:46:58 -0400937 if aidlDep != nil {
938 if lib, ok := module.linker.(*libraryDecorator); ok {
939 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
940 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
941 } else {
942 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
943 }
944 }
945 }
Liz Kammer12615db2021-09-28 09:19:17 -0400946
Spandan Dasdf4c2132023-05-09 23:58:52 +0000947 // Create a cc_yacc_static_library if srcs contains .y/.yy files
948 // This internal target will produce an .a file that will be statically linked to the parent library
949 if yaccDep := bp2buildCcYaccLibrary(ctx, compilerAttrs, linkerAttrs); yaccDep != nil {
950 (&linkerAttrs).implementationWholeArchiveDeps.Add(yaccDep)
951 }
952
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000953 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
954 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
955 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
956
Vinh Tran99270ea2022-11-28 11:15:23 -0500957 if module.afdo != nil && module.afdo.Properties.Afdo {
958 fdoProfileDep := bp2buildFdoProfile(ctx, module)
959 if fdoProfileDep != nil {
960 (&compilerAttrs).fdoProfile.SetValue(*fdoProfileDep)
961 }
962 }
963
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000964 if !compilerAttrs.syspropSrcs.IsEmpty() {
965 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
966 }
967
Zi Wang9f609db2023-01-04 11:06:54 -0800968 linkerAttrs.wholeArchiveDeps.Prepend = true
969 linkerAttrs.deps.Prepend = true
970 compilerAttrs.localIncludes.Prepend = true
971 compilerAttrs.absoluteIncludes.Prepend = true
972 compilerAttrs.hdrs.Prepend = true
973
Alixe2667872023-04-24 14:57:32 +0000974 convertedRsSrcs, rsAbsIncludes, rsLocalIncludes := bp2buildRScript(ctx, module, compilerAttrs)
975 (&compilerAttrs).srcs.Add(&convertedRsSrcs)
976 (&compilerAttrs).absoluteIncludes.Append(rsAbsIncludes)
977 (&compilerAttrs).localIncludes.Append(rsLocalIncludes)
978 (&compilerAttrs).localIncludes.Value = android.FirstUniqueStrings(compilerAttrs.localIncludes.Value)
979
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000980 features := compilerAttrs.features.Clone().Append(linkerAttrs.features).Append(bp2buildSanitizerFeatures(ctx, module))
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +0000981 features = features.Append(bp2buildLtoFeatures(ctx, module))
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000982 features = features.Append(convertHiddenVisibilityToFeatureBase(ctx, module))
Cole Faust5fa4e962022-08-22 14:31:04 -0700983 features.DeduplicateAxesFromBase()
984
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +0000985 addMuslSystemDynamicDeps(ctx, linkerAttrs)
986
Liz Kammere6583482021-10-19 13:56:10 -0400987 return baseAttributes{
988 compilerAttrs,
989 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -0700990 *features,
Liz Kammer12615db2021-09-28 09:19:17 -0400991 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -0400992 aidlDep,
Yu Liuf01a0f02022-12-07 15:45:30 -0800993 nativeCoverage,
Jingwen Chen107c0de2021-04-09 10:43:12 +0000994 }
995}
996
Spandan Dasdf4c2132023-05-09 23:58:52 +0000997type ccYaccLibraryAttributes struct {
998 Src bazel.LabelAttribute
999 Flags bazel.StringListAttribute
1000 Gen_location_hh bazel.BoolAttribute
1001 Gen_position_hh bazel.BoolAttribute
1002 Local_includes bazel.StringListAttribute
1003 Implementation_deps bazel.LabelListAttribute
1004 Implementation_dynamic_deps bazel.LabelListAttribute
1005}
1006
1007func bp2buildCcYaccLibrary(ctx android.Bp2buildMutatorContext, ca compilerAttributes, la linkerAttributes) *bazel.LabelAttribute {
1008 if ca.yaccSrc == nil {
1009 return nil
1010 }
1011 yaccLibraryLabel := ctx.Module().Name() + "_yacc"
1012 ctx.CreateBazelTargetModule(
1013 bazel.BazelTargetModuleProperties{
1014 Rule_class: "cc_yacc_static_library",
1015 Bzl_load_location: "//build/bazel/rules/cc:cc_yacc_library.bzl",
1016 },
1017 android.CommonAttributes{
1018 Name: yaccLibraryLabel,
1019 },
1020 &ccYaccLibraryAttributes{
1021 Src: *ca.yaccSrc,
1022 Flags: ca.yaccFlags,
1023 Gen_location_hh: ca.yaccGenLocationHeader,
1024 Gen_position_hh: ca.yaccGenPositionHeader,
1025 Local_includes: ca.localIncludes,
1026 Implementation_deps: la.implementationDeps,
1027 Implementation_dynamic_deps: la.implementationDynamicDeps,
1028 },
1029 )
1030
1031 yaccLibrary := &bazel.LabelAttribute{
1032 Value: &bazel.Label{
1033 Label: ":" + yaccLibraryLabel,
1034 },
1035 }
1036 return yaccLibrary
1037}
1038
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +00001039// As a workaround for b/261657184, we are manually adding the default value
1040// of system_dynamic_deps for the linux_musl os.
1041// TODO: Solve this properly
1042func addMuslSystemDynamicDeps(ctx android.Bp2buildMutatorContext, attrs linkerAttributes) {
1043 systemDynamicDeps := attrs.systemDynamicDeps.SelectValue(bazel.OsConfigurationAxis, "linux_musl")
1044 if attrs.systemDynamicDeps.HasAxisSpecificValues(bazel.OsConfigurationAxis) && systemDynamicDeps.IsNil() {
1045 attrs.systemDynamicDeps.SetSelectValue(bazel.OsConfigurationAxis, "linux_musl", android.BazelLabelForModuleDeps(ctx, config.MuslDefaultSharedLibraries))
1046 }
1047}
1048
Vinh Tran99270ea2022-11-28 11:15:23 -05001049type fdoProfileAttributes struct {
1050 Absolute_path_profile string
1051}
1052
1053func bp2buildFdoProfile(
1054 ctx android.Bp2buildMutatorContext,
1055 m *Module,
1056) *bazel.Label {
1057 for _, project := range globalAfdoProfileProjects {
Vinh Tranbc9c8b42022-12-09 12:03:52 -05001058 // Ensure handcrafted BUILD file exists in the project
1059 BUILDPath := android.ExistentPathForSource(ctx, project, "BUILD")
1060 if BUILDPath.Valid() {
1061 // We handcraft a BUILD file with fdo_profile targets that use the existing profiles in the project
1062 // This implementation is assuming that every afdo profile in globalAfdoProfileProjects already has
1063 // an associated fdo_profile target declared in the same package.
1064 // TODO(b/260714900): Handle arch-specific afdo profiles (e.g. `<module-name>-arm<64>.afdo`)
1065 path := android.ExistentPathForSource(ctx, project, m.Name()+".afdo")
1066 if path.Valid() {
1067 // FIXME: Some profiles only exist internally and are not released to AOSP.
1068 // When generated BUILD files are checked in, we'll run into merge conflict.
1069 // The cc_library_shared target in AOSP won't have reference to an fdo_profile target because
1070 // the profile doesn't exist. Internally, the same cc_library_shared target will
1071 // have reference to the fdo_profile.
1072 // For more context, see b/258682955#comment2
1073 fdoProfileLabel := "//" + strings.TrimSuffix(project, "/") + ":" + m.Name()
1074 return &bazel.Label{
1075 Label: fdoProfileLabel,
1076 }
Vinh Tran99270ea2022-11-28 11:15:23 -05001077 }
1078 }
1079 }
1080
1081 return nil
1082}
1083
Vinh Tran9f6796a2022-08-16 13:10:31 -04001084func bp2buildCcAidlLibrary(
1085 ctx android.Bp2buildMutatorContext,
1086 m *Module,
Vinh Tran367d89d2023-04-28 11:21:25 -04001087 aidlSrcs bazel.LabelListAttribute,
1088 aidlLibs bazel.LabelListAttribute,
Vinh Tran395a1e92022-09-16 18:27:29 -04001089 linkerAttrs linkerAttributes,
Vinh Trane6842942023-04-28 11:21:25 -04001090 compilerAttrs compilerAttributes,
Vinh Tran9f6796a2022-08-16 13:10:31 -04001091) *bazel.LabelAttribute {
Vinh Tran367d89d2023-04-28 11:21:25 -04001092 var aidlLibsFromSrcs, aidlFiles bazel.LabelListAttribute
1093 apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), ctx.Module())
1094
1095 if !aidlSrcs.IsEmpty() {
1096 aidlLibsFromSrcs, aidlFiles = aidlSrcs.Partition(func(src bazel.Label) bool {
Vinh Trana3b8b782022-09-14 11:40:24 -04001097 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
1098 fg.ShouldConvertToAidlLibrary(ctx) {
1099 return true
1100 }
1101 return false
1102 })
Vinh Tran9f6796a2022-08-16 13:10:31 -04001103
Vinh Tran367d89d2023-04-28 11:21:25 -04001104 if !aidlFiles.IsEmpty() {
Vinh Trana3b8b782022-09-14 11:40:24 -04001105 aidlLibName := m.Name() + "_aidl_library"
1106 ctx.CreateBazelTargetModule(
1107 bazel.BazelTargetModuleProperties{
1108 Rule_class: "aidl_library",
Sam Delmericoe55bf082023-03-31 09:47:28 -04001109 Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
Vinh Trana3b8b782022-09-14 11:40:24 -04001110 },
Vinh Tran367d89d2023-04-28 11:21:25 -04001111 android.CommonAttributes{
1112 Name: aidlLibName,
Liz Kammer2b3f56e2023-03-23 11:51:49 -04001113 Tags: apexAvailableTags,
Vinh Trana3b8b782022-09-14 11:40:24 -04001114 },
Vinh Tran367d89d2023-04-28 11:21:25 -04001115 &aidlLibraryAttributes{
1116 Srcs: aidlFiles,
Vinh Trana3b8b782022-09-14 11:40:24 -04001117 },
1118 )
Vinh Tran367d89d2023-04-28 11:21:25 -04001119 aidlLibsFromSrcs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
Vinh Trana3b8b782022-09-14 11:40:24 -04001120 }
Vinh Tran9f6796a2022-08-16 13:10:31 -04001121 }
1122
Vinh Tran367d89d2023-04-28 11:21:25 -04001123 allAidlLibs := aidlLibs.Clone()
1124 allAidlLibs.Append(aidlLibsFromSrcs)
1125
1126 if !allAidlLibs.IsEmpty() {
1127 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
1128 // Since parent cc_library already has these dependencies, we can add them as implementation
1129 // deps so that they don't re-export
1130 implementationDeps := linkerAttrs.deps.Clone()
1131 implementationDeps.Append(linkerAttrs.implementationDeps)
1132 implementationDynamicDeps := linkerAttrs.dynamicDeps.Clone()
1133 implementationDynamicDeps.Append(linkerAttrs.implementationDynamicDeps)
1134
1135 sdkAttrs := bp2BuildParseSdkAttributes(m)
1136
Vinh Trane6842942023-04-28 11:21:25 -04001137 exportedIncludes := bp2BuildParseExportedIncludes(ctx, m, &compilerAttrs.includes)
1138 includeAttrs := includesAttributes{
1139 Export_includes: exportedIncludes.Includes,
1140 Export_absolute_includes: exportedIncludes.AbsoluteIncludes,
1141 Export_system_includes: exportedIncludes.SystemIncludes,
1142 Local_includes: compilerAttrs.localIncludes,
1143 Absolute_includes: compilerAttrs.absoluteIncludes,
1144 }
1145
Vinh Tran367d89d2023-04-28 11:21:25 -04001146 ctx.CreateBazelTargetModule(
1147 bazel.BazelTargetModuleProperties{
1148 Rule_class: "cc_aidl_library",
1149 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
1150 },
1151 android.CommonAttributes{Name: ccAidlLibrarylabel},
1152 &ccAidlLibraryAttributes{
1153 Deps: *allAidlLibs,
1154 Implementation_deps: *implementationDeps,
1155 Implementation_dynamic_deps: *implementationDynamicDeps,
1156 Tags: apexAvailableTags,
1157 sdkAttributes: sdkAttrs,
Vinh Trane6842942023-04-28 11:21:25 -04001158 includesAttributes: includeAttrs,
Vinh Tran367d89d2023-04-28 11:21:25 -04001159 },
1160 )
1161 label := &bazel.LabelAttribute{
1162 Value: &bazel.Label{
1163 Label: ":" + ccAidlLibrarylabel,
1164 },
1165 }
1166 return label
1167 }
1168
Vinh Trana3b8b782022-09-14 11:40:24 -04001169 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -04001170}
1171
Yu Liufc603162022-03-01 15:44:08 -08001172func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +00001173 return sdkAttributes{
1174 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -08001175 Min_sdk_version: module.Properties.Min_sdk_version,
1176 }
1177}
1178
1179type sdkAttributes struct {
1180 Sdk_version *string
1181 Min_sdk_version *string
1182}
1183
Jingwen Chen107c0de2021-04-09 10:43:12 +00001184// Convenience struct to hold all attributes parsed from linker properties.
1185type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -05001186 deps bazel.LabelListAttribute
1187 implementationDeps bazel.LabelListAttribute
1188 dynamicDeps bazel.LabelListAttribute
1189 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -07001190 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -05001191 wholeArchiveDeps bazel.LabelListAttribute
1192 implementationWholeArchiveDeps bazel.LabelListAttribute
1193 systemDynamicDeps bazel.LabelListAttribute
Liz Kammerb4928432023-06-02 18:43:36 -04001194 usedSystemDynamicDepAsStaticDep map[string]bool
Liz Kammer54309532021-12-14 12:21:22 -05001195 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -04001196
Rupert Shuttleworth484aa252021-12-10 07:22:53 -05001197 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001198 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -04001199 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001200 stripKeepSymbols bazel.BoolAttribute
1201 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
1202 stripKeepSymbolsList bazel.StringListAttribute
1203 stripAll bazel.BoolAttribute
1204 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -04001205 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -04001206}
1207
Liz Kammer54309532021-12-14 12:21:22 -05001208var (
1209 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -04001210 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -05001211)
1212
Vinh Tran85fb07c2022-09-16 16:17:48 -04001213// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
1214// since all libs are already excluded by default
Liz Kammer748d7072023-01-25 12:07:43 -05001215func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, props *BaseLinkerProperties) {
1216 excludeSharedLibs := bazelLabelForSharedDeps(ctx, props.Target.Apex.Exclude_shared_libs)
1217 sharedExcludes := bazel.LabelList{Excludes: excludeSharedLibs.Includes}
1218 sharedExcludesLabelList := bazel.LabelListAttribute{}
1219 sharedExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, sharedExcludes)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001220
Liz Kammer748d7072023-01-25 12:07:43 -05001221 la.dynamicDeps.Append(sharedExcludesLabelList)
1222 la.implementationDynamicDeps.Append(sharedExcludesLabelList)
1223
1224 excludeStaticLibs := bazelLabelForStaticDeps(ctx, props.Target.Apex.Exclude_static_libs)
1225 staticExcludes := bazel.LabelList{Excludes: excludeStaticLibs.Includes}
1226 staticExcludesLabelList := bazel.LabelListAttribute{}
1227 staticExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, staticExcludes)
1228
1229 la.deps.Append(staticExcludesLabelList)
1230 la.implementationDeps.Append(staticExcludesLabelList)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001231}
1232
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001233func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, module *Module, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
1234 isBinary := module.Binary()
Liz Kammere6583482021-10-19 13:56:10 -04001235 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
1236 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -04001237
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001238 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -04001239 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
1240 if axis == bazel.NoConfigAxis {
1241 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
1242 if proptools.Bool(props.Use_version_lib) {
1243 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
1244 // remove from static libs so there is no duplicate dependency
1245 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
1246 // only add the dep if it is not in progress
1247 if !versionLibAlreadyInDeps {
Yu Liufe978fd2023-04-24 16:37:18 -07001248 wholeStaticLibs = append(wholeStaticLibs, versionLib)
Liz Kammerbaced712022-09-16 09:01:29 -04001249 }
1250 }
1251 }
1252
Liz Kammere6583482021-10-19 13:56:10 -04001253 // Excludes to parallel Soong:
1254 // 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 -04001255 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001256
Liz Kammerb4928432023-06-02 18:43:36 -04001257 if isBinary && module.StaticExecutable() {
1258 usedSystemStatic := android.FilterListPred(staticLibs, func(s string) bool {
1259 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, props.Exclude_static_libs)
1260 })
1261
1262 for _, el := range usedSystemStatic {
1263 if la.usedSystemDynamicDepAsStaticDep == nil {
1264 la.usedSystemDynamicDepAsStaticDep = map[string]bool{}
1265 }
1266 la.usedSystemDynamicDepAsStaticDep[el] = true
1267 }
1268 }
Vinh Tran85fb07c2022-09-16 16:17:48 -04001269 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1270 ctx,
1271 !isBinary,
1272 staticLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001273 props.Exclude_static_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001274 props.Export_static_lib_headers,
1275 bazelLabelForStaticDepsExcludes,
1276 )
Liz Kammer7a210ac2021-09-22 15:52:58 -04001277
Liz Kammere6583482021-10-19 13:56:10 -04001278 headerLibs := android.FirstUniqueStrings(props.Header_libs)
1279 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -04001280
Liz Kammere6583482021-10-19 13:56:10 -04001281 (&hDeps.export).Append(staticDeps.export)
1282 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001283
Liz Kammere6583482021-10-19 13:56:10 -04001284 (&hDeps.implementation).Append(staticDeps.implementation)
1285 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -04001286
Liz Kammere6583482021-10-19 13:56:10 -04001287 systemSharedLibs := props.System_shared_libs
1288 // systemSharedLibs distinguishes between nil/empty list behavior:
1289 // nil -> use default values
1290 // empty list -> no values specified
1291 if len(systemSharedLibs) > 0 {
1292 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
1293 }
1294 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
1295
1296 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -05001297 excludeSharedLibs := props.Exclude_shared_libs
1298 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
1299 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
1300 })
Liz Kammerb4928432023-06-02 18:43:36 -04001301
Liz Kammer54309532021-12-14 12:21:22 -05001302 for _, el := range usedSystem {
1303 if la.usedSystemDynamicDepAsDynamicDep == nil {
1304 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
1305 }
1306 la.usedSystemDynamicDepAsDynamicDep[el] = true
1307 }
1308
Vinh Tran85fb07c2022-09-16 16:17:48 -04001309 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1310 ctx,
1311 !isBinary,
1312 sharedLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001313 props.Exclude_shared_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001314 props.Export_shared_lib_headers,
1315 bazelLabelForSharedDepsExcludes,
1316 )
Liz Kammere6583482021-10-19 13:56:10 -04001317 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
1318 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Liz Kammer748d7072023-01-25 12:07:43 -05001319 la.resolveTargetApexProp(ctx, props)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001320
Wei Li81852ca2022-07-27 00:22:06 -07001321 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
Yu Liu10174ff2023-02-21 12:05:26 -08001322 // If a dependency in la.implementationDynamicDeps or la.dynamicDeps has stubs, its
1323 // stub variant should be used when the dependency is linked in a APEX. The
1324 // dependencies in NoConfigAxis and OsConfigurationAxis/OsAndroid are grouped by
1325 // having stubs or not, so Bazel select() statement can be used to choose
1326 // source/stub variants of them.
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001327 apexAvailable := module.ApexAvailable()
Spandan Dasac693b22023-04-24 00:07:38 +00001328 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.export, &la.dynamicDeps, 0, false)
1329 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.implementation, &la.implementationDynamicDeps, 1, false)
1330 if len(systemSharedLibs) > 0 {
1331 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, bazelLabelForSharedDeps(ctx, systemSharedLibs), &la.systemDynamicDeps, 2, true)
1332 }
Wei Li81852ca2022-07-27 00:22:06 -07001333 }
Liz Kammere6583482021-10-19 13:56:10 -04001334
1335 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1336 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1337 }
1338
1339 if Bool(props.Allow_undefined_symbols) {
1340 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1341 }
1342
1343 var linkerFlags []string
1344 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001345 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001346 // binaries remove static flag if -shared is in the linker flags
1347 if isBinary && android.InList("-shared", linkerFlags) {
1348 axisFeatures = append(axisFeatures, "-static_flag")
1349 }
1350 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001351
Alex Márquez Pérez Muñíz Díaz Puras Thaureaux01ec55e2023-01-30 22:53:04 +00001352 if !props.libCrt() {
1353 axisFeatures = append(axisFeatures, "-use_libcrt")
1354 }
1355 if !props.crt() {
1356 axisFeatures = append(axisFeatures, "-link_crt")
1357 }
1358
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001359 // This must happen before the addition of flags for Version Script and
1360 // Dynamic List, as these flags must be split on spaces and those must not
1361 linkerFlags = parseCommandLineFlags(linkerFlags, filterOutClangUnknownCflags)
1362
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001363 additionalLinkerInputs := bazel.LabelList{}
Liz Kammere6583482021-10-19 13:56:10 -04001364 if props.Version_script != nil {
1365 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001366 additionalLinkerInputs.Add(&label)
Liz Kammere6583482021-10-19 13:56:10 -04001367 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
Trevor Radcliffef06dd912023-05-19 14:51:41 +00001368 axisFeatures = append(axisFeatures, "android_cfi_exports_map")
Liz Kammere6583482021-10-19 13:56:10 -04001369 }
Alix773adaa2022-04-27 17:49:34 +00001370
1371 if props.Dynamic_list != nil {
1372 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001373 additionalLinkerInputs.Add(&label)
Alix773adaa2022-04-27 17:49:34 +00001374 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1375 }
1376
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001377 la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
Spandan Dasfb04c412023-05-15 18:35:36 +00001378 if axis == bazel.OsConfigurationAxis && (config == bazel.OsDarwin || config == bazel.OsLinux || config == bazel.OsWindows) {
1379 linkerFlags = append(linkerFlags, props.Host_ldlibs...)
1380 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001381 la.linkopts.SetSelectValue(axis, config, linkerFlags)
Liz Kammere6583482021-10-19 13:56:10 -04001382
1383 if axisFeatures != nil {
1384 la.features.SetSelectValue(axis, config, axisFeatures)
1385 }
Cole Faust6b29f592022-08-09 09:50:56 -07001386
1387 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1388 if !runtimeDeps.IsEmpty() {
1389 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1390 }
Liz Kammere6583482021-10-19 13:56:10 -04001391}
1392
Spandan Das2518c022023-03-17 03:02:32 +00001393var (
1394 apiSurfaceModuleLibCurrentPackage = "@api_surfaces//" + android.ModuleLibApi.String() + "/current:"
1395)
1396
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001397func availableToSameApexes(a, b []string) bool {
1398 if len(a) == 0 && len(b) == 0 {
1399 return true
1400 }
1401 differ, _, _ := android.ListSetDifference(a, b)
1402 return !differ
1403}
1404
Spandan Das4242f102023-04-19 22:31:54 +00001405var (
Spandan Das9cad90f2023-05-04 17:15:44 +00001406 apiDomainConfigSettingKey = android.NewOnceKey("apiDomainConfigSettingKey")
1407 apiDomainConfigSettingLock sync.Mutex
Spandan Das4242f102023-04-19 22:31:54 +00001408)
1409
Spandan Das9cad90f2023-05-04 17:15:44 +00001410func getApiDomainConfigSettingMap(config android.Config) *map[string]bool {
1411 return config.Once(apiDomainConfigSettingKey, func() interface{} {
Spandan Das4242f102023-04-19 22:31:54 +00001412 return &map[string]bool{}
1413 }).(*map[string]bool)
1414}
1415
Spandan Das9cad90f2023-05-04 17:15:44 +00001416var (
1417 testApexNameToApiDomain = map[string]string{
1418 "test_broken_com.android.art": "com.android.art",
1419 }
1420)
1421
Spandan Dasa43ae132023-05-08 18:33:16 +00001422// GetApiDomain returns the canonical name of the apex. This is synonymous to the apex_name definition.
1423// https://cs.android.com/android/_/android/platform/build/soong/+/e3f0281b8897da1fe23b2f4f3a05f1dc87bcc902:apex/prebuilt.go;l=81-83;drc=2dc7244af985a6ad701b22f1271e606cabba527f;bpv=1;bpt=0
1424// For test apexes, it uses a naming convention heuristic to determine the api domain.
1425// TODO (b/281548611): Move this build/soong/android
1426func GetApiDomain(apexName string) string {
Spandan Das9cad90f2023-05-04 17:15:44 +00001427 if apiDomain, exists := testApexNameToApiDomain[apexName]; exists {
1428 return apiDomain
1429 }
1430 // Remove `test_` prefix
1431 return strings.TrimPrefix(apexName, "test_")
1432}
1433
Spandan Das4242f102023-04-19 22:31:54 +00001434// Create a config setting for this apex in build/bazel/rules/apex
1435// The use case for this is stub/impl selection in cc libraries
1436// Long term, these config_setting(s) should be colocated with the respective apex definitions.
1437// Note that this is an anti-pattern: The config_setting should be created from the apex definition
1438// and not from a cc_library.
1439// This anti-pattern is needed today since not all apexes have been allowlisted.
1440func createInApexConfigSetting(ctx android.TopDownMutatorContext, apexName string) {
1441 if apexName == android.AvailableToPlatform || apexName == android.AvailableToAnyApex {
1442 // These correspond to android-non_apex and android-in_apex
1443 return
1444 }
Spandan Das9cad90f2023-05-04 17:15:44 +00001445 apiDomainConfigSettingLock.Lock()
1446 defer apiDomainConfigSettingLock.Unlock()
Spandan Das4242f102023-04-19 22:31:54 +00001447
1448 // Return if a config_setting has already been created
Spandan Dasa43ae132023-05-08 18:33:16 +00001449 apiDomain := GetApiDomain(apexName)
Spandan Das9cad90f2023-05-04 17:15:44 +00001450 acsm := getApiDomainConfigSettingMap(ctx.Config())
1451 if _, exists := (*acsm)[apiDomain]; exists {
Spandan Das4242f102023-04-19 22:31:54 +00001452 return
1453 }
Spandan Das9cad90f2023-05-04 17:15:44 +00001454 (*acsm)[apiDomain] = true
Spandan Das4242f102023-04-19 22:31:54 +00001455
1456 csa := bazel.ConfigSettingAttributes{
1457 Flag_values: bazel.StringMapAttribute{
Spandan Das9cad90f2023-05-04 17:15:44 +00001458 "//build/bazel/rules/apex:api_domain": apiDomain,
Spandan Das4242f102023-04-19 22:31:54 +00001459 },
Spandan Das9cad90f2023-05-04 17:15:44 +00001460 // Constraint this to android
1461 Constraint_values: bazel.MakeLabelListAttribute(
1462 bazel.MakeLabelList(
1463 []bazel.Label{
1464 bazel.Label{Label: "//build/bazel/platforms/os:android"},
1465 },
1466 ),
1467 ),
Spandan Das4242f102023-04-19 22:31:54 +00001468 }
1469 ca := android.CommonAttributes{
Spandan Das9cad90f2023-05-04 17:15:44 +00001470 Name: apiDomain,
Spandan Das4242f102023-04-19 22:31:54 +00001471 }
1472 ctx.CreateBazelConfigSetting(
1473 csa,
1474 ca,
1475 "build/bazel/rules/apex",
1476 )
1477}
1478
1479func inApexConfigSetting(apexAvailable string) string {
1480 if apexAvailable == android.AvailableToPlatform {
Spandan Das6d4d9da2023-04-18 06:20:40 +00001481 return bazel.AndroidPlatform
Spandan Das4242f102023-04-19 22:31:54 +00001482 }
1483 if apexAvailable == android.AvailableToAnyApex {
1484 return bazel.AndroidAndInApex
1485 }
Spandan Dasa43ae132023-05-08 18:33:16 +00001486 apiDomain := GetApiDomain(apexAvailable)
Spandan Das9cad90f2023-05-04 17:15:44 +00001487 return "//build/bazel/rules/apex:" + apiDomain
Spandan Das4242f102023-04-19 22:31:54 +00001488}
1489
Spandan Das6d4d9da2023-04-18 06:20:40 +00001490// Inputs to stub vs impl selection.
1491type stubSelectionInfo struct {
1492 // Label of the implementation library (e.g. //bionic/libc:libc)
1493 impl bazel.Label
1494 // Axis containing the implementation library
1495 axis bazel.ConfigurationAxis
1496 // Axis key containing the implementation library
1497 config string
1498 // API domain of the apex
1499 // For test apexes (test_com.android.foo), this will be the source apex (com.android.foo)
1500 apiDomain string
1501 // List of dep labels
1502 dynamicDeps *bazel.LabelListAttribute
1503 // Boolean value for determining if the dep is in the same api domain
1504 // If false, the label will be rewritten to to the stub label
1505 sameApiDomain bool
1506}
1507
1508func useStubOrImplInApexWithName(ssi stubSelectionInfo) {
1509 lib := ssi.impl
1510 if !ssi.sameApiDomain {
1511 lib = bazel.Label{
1512 Label: apiSurfaceModuleLibCurrentPackage + strings.TrimPrefix(lib.OriginalModuleName, ":"),
1513 }
1514 }
1515 // Create a select statement specific to this apex
1516 inApexSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain))
1517 (&inApexSelectValue).Append(bazel.MakeLabelList([]bazel.Label{lib}))
1518 ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain), bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1519 // Delete the library from the common config for this apex
1520 implDynamicDeps := ssi.dynamicDeps.SelectValue(ssi.axis, ssi.config)
1521 implDynamicDeps = bazel.SubtractBazelLabelList(implDynamicDeps, bazel.MakeLabelList([]bazel.Label{ssi.impl}))
1522 ssi.dynamicDeps.SetSelectValue(ssi.axis, ssi.config, implDynamicDeps)
1523 if ssi.axis == bazel.NoConfigAxis {
1524 // Set defaults. Defaults (i.e. host) should use impl and not stubs.
1525 defaultSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
1526 (&defaultSelectValue).Append(bazel.MakeLabelList([]bazel.Label{ssi.impl}))
1527 ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
1528 }
Liz Kammere6583482021-10-19 13:56:10 -04001529}
1530
Yu Liu10174ff2023-02-21 12:05:26 -08001531func setStubsForDynamicDeps(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis,
Spandan Dasac693b22023-04-24 00:07:38 +00001532 config string, apexAvailable []string, dynamicLibs bazel.LabelList, dynamicDeps *bazel.LabelListAttribute, ind int, buildNonApexWithStubs bool) {
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001533
Spandan Das4242f102023-04-19 22:31:54 +00001534 // Create a config_setting for each apex_available.
1535 // This will be used to select impl of a dep if dep is available to the same apex.
1536 for _, aa := range apexAvailable {
1537 createInApexConfigSetting(ctx.(android.TopDownMutatorContext), aa)
1538 }
1539
Spandan Das6d4d9da2023-04-18 06:20:40 +00001540 apiDomainForSelects := []string{}
1541 for _, apex := range apexAvailable {
1542 apiDomainForSelects = append(apiDomainForSelects, GetApiDomain(apex))
1543 }
1544 // Always emit a select statement for the platform variant.
1545 // This ensures that b build //foo --config=android works
1546 // Soong always creates a platform variant even when the library might not be available to platform.
1547 if !android.InList(android.AvailableToPlatform, apiDomainForSelects) {
1548 apiDomainForSelects = append(apiDomainForSelects, android.AvailableToPlatform)
1549 }
1550 apiDomainForSelects = android.SortedUniqueStrings(apiDomainForSelects)
1551
1552 // Create a select for each apex this library could be included in.
1553 for _, l := range dynamicLibs.Includes {
1554 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
1555 if c, ok := dep.(*Module); !ok || !c.HasStubsVariants() {
1556 continue
1557 }
1558 // TODO (b/280339069): Decrease the verbosity of the generated BUILD files
1559 for _, apiDomain := range apiDomainForSelects {
1560 var sameApiDomain bool
1561 if apiDomain == android.AvailableToPlatform {
1562 // Platform variants in Soong use equality of apex_available for stub/impl selection.
1563 // https://cs.android.com/android/_/android/platform/build/soong/+/316b0158fe57ee7764235923e7c6f3d530da39c6:cc/cc.go;l=3393-3404;drc=176271a426496fa2688efe2b40d5c74340c63375;bpv=1;bpt=0
1564 // One of the factors behind this design choice is cc_test
1565 // Tests only have a platform variant, and using equality of apex_available ensures
1566 // that tests of an apex library gets its implementation and not stubs.
1567 // TODO (b/280343104): Discuss if we can drop this special handling for platform variants.
1568 sameApiDomain = availableToSameApexes(apexAvailable, dep.(*Module).ApexAvailable())
Spandan Das6aaab9d2023-05-04 17:27:30 +00001569 if linkable, ok := ctx.Module().(LinkableInterface); ok && linkable.Bootstrap() {
1570 sameApiDomain = true
1571 }
Spandan Das6d4d9da2023-04-18 06:20:40 +00001572 } else {
1573 sameApiDomain = android.InList(apiDomain, dep.(*Module).ApexAvailable())
1574 }
1575 ssi := stubSelectionInfo{
1576 impl: l,
1577 axis: axis,
1578 config: config,
1579 apiDomain: apiDomain,
1580 dynamicDeps: dynamicDeps,
1581 sameApiDomain: sameApiDomain,
1582 }
1583 useStubOrImplInApexWithName(ssi)
1584 }
1585 }
Yu Liu10174ff2023-02-21 12:05:26 -08001586}
1587
Jingwen Chen55bc8202021-11-02 06:40:51 +00001588func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001589 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1590 if stripProperties, ok := props.(*StripProperties); ok {
1591 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1592 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1593 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1594 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1595 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001596 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001597 })
Liz Kammere6583482021-10-19 13:56:10 -04001598}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001599
Jingwen Chen55bc8202021-11-02 06:40:51 +00001600func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001601
Liz Kammer47535c52021-06-02 16:02:22 -04001602 type productVarDep struct {
1603 // the name of the corresponding excludes field, if one exists
1604 excludesField string
1605 // reference to the bazel attribute that should be set for the given product variable config
1606 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001607
Jingwen Chen55bc8202021-11-02 06:40:51 +00001608 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001609 }
1610
Zi Wang0a8a1292022-08-30 06:27:01 +00001611 // an intermediate attribute that holds Header_libs info, and will be appended to
1612 // implementationDeps at the end, to solve the confliction that both header_libs
1613 // and static_libs use implementationDeps.
1614 var headerDeps bazel.LabelListAttribute
1615
Liz Kammer47535c52021-06-02 16:02:22 -04001616 productVarToDepFields := map[string]productVarDep{
1617 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001618 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1619 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1620 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001621 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001622 }
1623
Liz Kammer47535c52021-06-02 16:02:22 -04001624 for name, dep := range productVarToDepFields {
1625 props, exists := productVariableProps[name]
1626 excludeProps, excludesExists := productVariableProps[dep.excludesField]
Sasha Smundak39a301c2022-12-29 17:11:49 -08001627 // if neither an include nor excludes property exists, then skip it
Liz Kammer47535c52021-06-02 16:02:22 -04001628 if !exists && !excludesExists {
1629 continue
1630 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001631 // Collect all the configurations that an include or exclude property exists for.
1632 // We want to iterate all configurations rather than either the include or exclude because, for a
1633 // particular configuration, we may have either only an include or an exclude to handle.
Cole Faust150f9a52023-04-26 10:52:24 -07001634 productConfigProps := make(map[android.ProductConfigOrSoongConfigProperty]bool, len(props)+len(excludeProps))
Jingwen Chen25825ca2021-11-15 12:28:43 +00001635 for p := range props {
1636 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001637 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001638 for p := range excludeProps {
1639 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001640 }
1641
Jingwen Chen25825ca2021-11-15 12:28:43 +00001642 for productConfigProp := range productConfigProps {
1643 prop, includesExists := props[productConfigProp]
1644 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001645 var includes, excludes []string
1646 var ok bool
1647 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001648 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001649 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1650 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001651 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001652 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1653 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001654
Jingwen Chen58ff6802021-11-17 12:14:41 +00001655 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001656 dep.attribute.SetSelectValue(
1657 productConfigProp.ConfigurationAxis(),
1658 productConfigProp.SelectKey(),
1659 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1660 )
Liz Kammer47535c52021-06-02 16:02:22 -04001661 }
1662 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001663 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001664}
Liz Kammer47535c52021-06-02 16:02:22 -04001665
Liz Kammer54309532021-12-14 12:21:22 -05001666func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1667 // if system dynamic deps have the default value, any use of a system dynamic library used will
1668 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001669 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001670 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -08001671 toRemove := bazelLabelForSharedDeps(ctx, android.SortedKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001672 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001673 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1674 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001675 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001676 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1677 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001678
1679 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001680 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1681 for _, lib := range toRemove.Includes {
Spandan Das2518c022023-03-17 03:02:32 +00001682 stubLabelInApiSurfaces := bazel.Label{
1683 Label: apiSurfaceModuleLibCurrentPackage + lib.OriginalModuleName,
1684 }
1685 stubsToRemove = append(stubsToRemove, stubLabelInApiSurfaces)
Liz Kammer91487d42022-09-13 11:27:11 -04001686 }
Spandan Das6d4d9da2023-04-18 06:20:40 +00001687 // system libraries (e.g. libc, libm, libdl) belong the com.android.runtime api domain
1688 // dedupe the stubs of these libraries from the other api domains (platform, other_apexes...)
1689 for _, aa := range ctx.Module().(*Module).ApexAvailable() {
1690 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, inApexConfigSetting(aa), bazel.MakeLabelList(stubsToRemove))
1691 }
1692 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidPlatform, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001693 }
Liz Kammerb4928432023-06-02 18:43:36 -04001694 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsStaticDep) > 0 {
1695 toRemove := bazelLabelForStaticDeps(ctx, android.SortedKeys(la.usedSystemDynamicDepAsStaticDep))
1696 la.deps.Exclude(bazel.NoConfigAxis, "", toRemove)
1697 la.deps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1698 la.deps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
1699 la.implementationDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
1700 la.implementationDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1701 la.implementationDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
1702 }
Liz Kammer54309532021-12-14 12:21:22 -05001703
Liz Kammere6583482021-10-19 13:56:10 -04001704 la.deps.ResolveExcludes()
1705 la.implementationDeps.ResolveExcludes()
1706 la.dynamicDeps.ResolveExcludes()
1707 la.implementationDynamicDeps.ResolveExcludes()
1708 la.wholeArchiveDeps.ResolveExcludes()
1709 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001710
Jingwen Chen91220d72021-03-24 02:18:33 -04001711}
1712
Jingwen Chened9c17d2021-04-13 07:14:55 +00001713// Relativize a list of root-relative paths with respect to the module's
1714// directory.
1715//
1716// include_dirs Soong prop are root-relative (b/183742505), but
1717// local_include_dirs, export_include_dirs and export_system_include_dirs are
1718// module dir relative. This function makes a list of paths entirely module dir
1719// relative.
1720//
1721// For the `include` attribute, Bazel wants the paths to be relative to the
1722// module.
1723func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001724 var relativePaths []string
1725 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001726 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1727 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1728 if err != nil {
1729 panic(err)
1730 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001731 relativePaths = append(relativePaths, relativePath)
1732 }
1733 return relativePaths
1734}
1735
Liz Kammer5fad5012021-09-09 14:08:21 -04001736// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1737// attributes.
1738type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001739 AbsoluteIncludes bazel.StringListAttribute
1740 Includes bazel.StringListAttribute
1741 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001742}
1743
Liz Kammer54549442022-05-11 13:55:06 -04001744func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001745 var exported BazelIncludes
1746 if includes != nil {
1747 exported = *includes
1748 } else {
1749 exported = BazelIncludes{}
1750 }
Zi Wang1cb11802022-12-09 16:08:54 -08001751
1752 // cc library Export_include_dirs and Export_system_include_dirs are marked
1753 // "variant_prepend" in struct tag, set their prepend property to true to make
1754 // sure bp2build generates correct result.
1755 exported.Includes.Prepend = true
1756 exported.SystemIncludes.Prepend = true
1757
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001758 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1759 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1760 if len(flagExporterProperties.Export_include_dirs) > 0 {
1761 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1762 }
1763 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1764 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 -04001765 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001766 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001767 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001768 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001769 exported.Includes.DeduplicateAxesFromBase()
1770 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001771
Liz Kammer5fad5012021-09-09 14:08:21 -04001772 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001773}
Chris Parsons953b3562021-09-20 15:14:39 -04001774
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001775func BazelLabelNameForStaticModule(baseLabel string) string {
1776 return baseLabel + "_bp2build_cc_library_static"
1777}
1778
Jingwen Chen55bc8202021-11-02 06:40:51 +00001779func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001780 label := android.BazelModuleLabel(ctx, m)
Sasha Smundak39a301c2022-12-29 17:11:49 -08001781 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001782 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001783 }
1784 return label
1785}
1786
Jingwen Chen55bc8202021-11-02 06:40:51 +00001787func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001788 // cc_library, at it's root name, propagates the shared library, which depends on the static
1789 // library.
1790 return android.BazelModuleLabel(ctx, m)
1791}
1792
Jingwen Chen55bc8202021-11-02 06:40:51 +00001793func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001794 label := bazelLabelForStaticModule(ctx, m)
1795 if aModule, ok := m.(android.Module); ok {
1796 if android.IsModulePrebuilt(aModule) {
1797 label += "_alwayslink"
1798 }
1799 }
1800 return label
1801}
1802
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04001803func xsdConfigCppTarget(xsd android.XsdConfigBp2buildTargets) string {
1804 return xsd.CppBp2buildTargetName()
Liz Kammer084d6a92023-06-22 16:23:53 -04001805}
1806
Jingwen Chen55bc8202021-11-02 06:40:51 +00001807func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001808 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1809}
1810
Jingwen Chen55bc8202021-11-02 06:40:51 +00001811func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001812 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1813}
1814
Jingwen Chen55bc8202021-11-02 06:40:51 +00001815func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001816 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1817}
1818
Jingwen Chen55bc8202021-11-02 06:40:51 +00001819func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001820 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1821}
1822
Jingwen Chen55bc8202021-11-02 06:40:51 +00001823func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001824 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1825}
1826
Jingwen Chen55bc8202021-11-02 06:40:51 +00001827func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001828 // This is not elegant, but bp2build's shared library targets only propagate
1829 // their header information as part of the normal C++ provider.
1830 return bazelLabelForSharedDeps(ctx, modules)
1831}
1832
Zi Wang0a8a1292022-08-30 06:27:01 +00001833func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1834 // This is only used when product_variable header_libs is processed, to follow
1835 // the pattern of depResolutionFunc
1836 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1837}
1838
Jingwen Chen55bc8202021-11-02 06:40:51 +00001839func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001840 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1841}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001842
1843type binaryLinkerAttrs struct {
1844 Linkshared *bool
Spandan Das39ccf932023-05-26 18:03:39 +00001845 Stem bazel.StringAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001846 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001847}
1848
Jingwen Chen55bc8202021-11-02 06:40:51 +00001849func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001850 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001851 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1852 linkerProps := props.(*BinaryLinkerProperties)
1853 staticExecutable := linkerProps.Static_executable
1854 if axis == bazel.NoConfigAxis {
1855 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1856 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001857 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001858 } else if staticExecutable != nil {
1859 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1860 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1861 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001862 }
Spandan Das39ccf932023-05-26 18:03:39 +00001863 if stem := linkerProps.Stem; stem != nil {
1864 attrs.Stem.SetSelectValue(axis, config, stem)
1865 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001866 if suffix := linkerProps.Suffix; suffix != nil {
1867 attrs.Suffix.SetSelectValue(axis, config, suffix)
1868 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001869 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001870
1871 return attrs
1872}
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001873
1874func bp2buildSanitizerFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1875 sanitizerFeatures := bazel.StringListAttribute{}
1876 bp2BuildPropParseHelper(ctx, m, &SanitizeProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1877 var features []string
1878 if sanitizerProps, ok := props.(*SanitizeProperties); ok {
1879 if sanitizerProps.Sanitize.Integer_overflow != nil && *sanitizerProps.Sanitize.Integer_overflow {
1880 features = append(features, "ubsan_integer_overflow")
1881 }
1882 for _, sanitizer := range sanitizerProps.Sanitize.Misc_undefined {
1883 features = append(features, "ubsan_"+sanitizer)
1884 }
Trevor Radcliffeded095c2023-06-12 19:18:28 +00001885 blocklist := sanitizerProps.Sanitize.Blocklist
1886 if blocklist != nil {
1887 // Format the blocklist name to be used in a feature name
1888 blocklistFeatureSuffix := strings.Replace(strings.ToLower(*blocklist), ".", "_", -1)
Trevor Radcliffed7148712023-07-10 18:50:47 +00001889 features = append(features, "sanitizer_blocklist_"+blocklistFeatureSuffix)
Trevor Radcliffeded095c2023-06-12 19:18:28 +00001890 }
Trevor Radcliffe523c5c62023-06-16 20:15:45 +00001891 if sanitizerProps.Sanitize.Cfi != nil && !proptools.Bool(sanitizerProps.Sanitize.Cfi) {
1892 features = append(features, "-android_cfi")
1893 } else if proptools.Bool(sanitizerProps.Sanitize.Cfi) {
Trevor Radcliffe27669c02023-03-28 20:47:10 +00001894 features = append(features, "android_cfi")
1895 if proptools.Bool(sanitizerProps.Sanitize.Config.Cfi_assembly_support) {
1896 features = append(features, "android_cfi_assembly_support")
1897 }
1898 }
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001899 sanitizerFeatures.SetSelectValue(axis, config, features)
1900 }
1901 })
1902 return sanitizerFeatures
1903}
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +00001904
1905func bp2buildLtoFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1906 lto_feature_name := "android_thin_lto"
1907 ltoBoolFeatures := bazel.BoolAttribute{}
1908 bp2BuildPropParseHelper(ctx, m, &LTOProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1909 if ltoProps, ok := props.(*LTOProperties); ok {
1910 thinProp := ltoProps.Lto.Thin != nil && *ltoProps.Lto.Thin
1911 thinPropSetToFalse := ltoProps.Lto.Thin != nil && !*ltoProps.Lto.Thin
1912 neverProp := ltoProps.Lto.Never != nil && *ltoProps.Lto.Never
1913 if thinProp {
1914 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(true))
1915 return
1916 }
1917 if neverProp || thinPropSetToFalse {
1918 if thinProp {
1919 ctx.ModuleErrorf("lto.thin and lto.never are mutually exclusive but were specified together")
1920 } else {
1921 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(false))
1922 }
1923 return
1924 }
1925 }
1926 ltoBoolFeatures.SetSelectValue(axis, config, nil)
1927 })
1928
1929 props := m.GetArchVariantProperties(ctx, &LTOProperties{})
1930 ltoStringFeatures, err := ltoBoolFeatures.ToStringListAttribute(func(boolPtr *bool, axis bazel.ConfigurationAxis, config string) []string {
1931 if boolPtr == nil {
1932 return []string{}
1933 }
1934 if !*boolPtr {
1935 return []string{"-" + lto_feature_name}
1936 }
1937 features := []string{lto_feature_name}
1938 if ltoProps, ok := props[axis][config].(*LTOProperties); ok {
1939 if ltoProps.Whole_program_vtables != nil && *ltoProps.Whole_program_vtables {
1940 features = append(features, "android_thin_lto_whole_program_vtables")
1941 }
1942 }
1943 return features
1944 })
1945 if err != nil {
1946 ctx.ModuleErrorf("Error processing LTO attributes: %s", err)
1947 }
1948 return ltoStringFeatures
1949}
Trevor Radcliffea8b44162023-04-14 18:25:24 +00001950
1951func convertHiddenVisibilityToFeatureBase(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1952 visibilityHiddenFeature := bazel.StringListAttribute{}
1953 bp2BuildPropParseHelper(ctx, m, &BaseCompilerProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1954 if baseCompilerProps, ok := props.(*BaseCompilerProperties); ok {
1955 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, baseCompilerProps.Cflags)
1956 }
1957 })
1958 return visibilityHiddenFeature
1959}
1960
1961func convertHiddenVisibilityToFeatureStaticOrShared(ctx android.BazelConversionPathContext, m *Module, isStatic bool) bazel.StringListAttribute {
1962 visibilityHiddenFeature := bazel.StringListAttribute{}
1963 if isStatic {
1964 bp2BuildPropParseHelper(ctx, m, &StaticProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1965 if staticProps, ok := props.(*StaticProperties); ok {
1966 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, staticProps.Static.Cflags)
1967 }
1968 })
1969 } else {
1970 bp2BuildPropParseHelper(ctx, m, &SharedProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
1971 if sharedProps, ok := props.(*SharedProperties); ok {
1972 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, sharedProps.Shared.Cflags)
1973 }
1974 })
1975 }
1976
1977 return visibilityHiddenFeature
1978}
1979
1980func convertHiddenVisibilityToFeatureHelper(feature *bazel.StringListAttribute, axis bazel.ConfigurationAxis, configString string, cflags []string) {
1981 if inList(config.VisibilityHiddenFlag, cflags) {
1982 feature.SetSelectValue(axis, configString, []string{"visibility_hidden"})
1983 }
1984}