blob: 601c0c54ebe5df454aa359dcb2deb5dff50ba2c5 [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
Spandan Dasa99348d2023-08-01 23:10:05 +000051 protoFromGenPartition = "proto_gen"
52
Liz Kammer5f5dbaa2023-07-17 17:44:08 -040053 hdrPartition = "hdr"
54
Liz Kammer91487d42022-09-13 11:27:11 -040055 stubsSuffix = "_stub_libs_current"
Liz Kammerae3994e2021-10-19 09:45:48 -040056)
57
Liz Kammer2222c6b2021-05-24 15:41:47 -040058// staticOrSharedAttributes are the Bazel-ified versions of StaticOrSharedProperties --
Jingwen Chenbcf53042021-05-26 04:42:42 +000059// properties which apply to either the shared or static version of a cc_library module.
Liz Kammer2222c6b2021-05-24 15:41:47 -040060type staticOrSharedAttributes struct {
Vinh Tran9f6796a2022-08-16 13:10:31 -040061 Srcs bazel.LabelListAttribute
62 Srcs_c bazel.LabelListAttribute
63 Srcs_as bazel.LabelListAttribute
64 Srcs_aidl bazel.LabelListAttribute
65 Hdrs bazel.LabelListAttribute
66 Copts bazel.StringListAttribute
Jingwen Chen14a8bda2021-06-02 11:10:02 +000067
Trevor Radcliffed9b7f172023-08-09 22:21:38 +000068 Additional_compiler_inputs bazel.LabelListAttribute
69
Liz Kammer12615db2021-09-28 09:19:17 -040070 Deps bazel.LabelListAttribute
71 Implementation_deps bazel.LabelListAttribute
72 Dynamic_deps bazel.LabelListAttribute
73 Implementation_dynamic_deps bazel.LabelListAttribute
74 Whole_archive_deps bazel.LabelListAttribute
75 Implementation_whole_archive_deps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -070076 Runtime_deps bazel.LabelListAttribute
Chris Parsons51f8c392021-08-03 21:01:05 -040077
78 System_dynamic_deps bazel.LabelListAttribute
Chris Parsons58852a02021-12-09 18:10:18 -050079
80 Enabled bazel.BoolAttribute
Yu Liufc603162022-03-01 15:44:08 -080081
Yu Liuf01a0f02022-12-07 15:45:30 -080082 Native_coverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -070083
Liz Kammeraceec252023-03-24 09:46:36 -040084 Apex_available []string
85
Trevor Radcliffea8b44162023-04-14 18:25:24 +000086 Features bazel.StringListAttribute
87
Yu Liufc603162022-03-01 15:44:08 -080088 sdkAttributes
Sam Delmericofb3bb322022-10-21 10:42:24 -040089
90 tidyAttributes
91}
92
93type tidyAttributes struct {
Sam Delmerico63f0c932023-03-14 14:05:28 -040094 Tidy *string
Sam Delmericofb3bb322022-10-21 10:42:24 -040095 Tidy_flags []string
96 Tidy_checks []string
97 Tidy_checks_as_errors []string
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -040098 Tidy_disabled_srcs bazel.LabelListAttribute
Sam Delmerico4c902d62022-11-02 14:17:15 -040099 Tidy_timeout_srcs bazel.LabelListAttribute
Sam Delmericofb3bb322022-10-21 10:42:24 -0400100}
101
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400102func (m *Module) convertTidyAttributes(ctx android.BaseMutatorContext, moduleAttrs *tidyAttributes) {
Sam Delmericofb3bb322022-10-21 10:42:24 -0400103 for _, f := range m.features {
104 if tidy, ok := f.(*tidyFeature); ok {
Sam Delmerico63f0c932023-03-14 14:05:28 -0400105 var tidyAttr *string
106 if tidy.Properties.Tidy != nil {
107 if *tidy.Properties.Tidy {
108 tidyAttr = proptools.StringPtr("local")
109 } else {
110 tidyAttr = proptools.StringPtr("never")
111 }
112 }
113 moduleAttrs.Tidy = tidyAttr
Sam Delmericofb3bb322022-10-21 10:42:24 -0400114 moduleAttrs.Tidy_flags = tidy.Properties.Tidy_flags
115 moduleAttrs.Tidy_checks = tidy.Properties.Tidy_checks
116 moduleAttrs.Tidy_checks_as_errors = tidy.Properties.Tidy_checks_as_errors
117 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400118
119 }
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400120 archVariantProps := m.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
121 for axis, configToProps := range archVariantProps {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800122 for cfg, _props := range configToProps {
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400123 if archProps, ok := _props.(*BaseCompilerProperties); ok {
124 archDisabledSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_disabled_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800125 moduleAttrs.Tidy_disabled_srcs.SetSelectValue(axis, cfg, archDisabledSrcs)
Sam Delmerico4c902d62022-11-02 14:17:15 -0400126 archTimeoutSrcs := android.BazelLabelForModuleSrc(ctx, archProps.Tidy_timeout_srcs)
Sasha Smundak39a301c2022-12-29 17:11:49 -0800127 moduleAttrs.Tidy_timeout_srcs.SetSelectValue(axis, cfg, archTimeoutSrcs)
Sam Delmericoc9b8fbd2022-10-25 15:47:17 -0400128 }
129 }
Sam Delmericofb3bb322022-10-21 10:42:24 -0400130 }
Jingwen Chen53681ef2021-04-29 08:15:13 +0000131}
132
Spandan Dasa99348d2023-08-01 23:10:05 +0000133// Returns an unchanged label and a bool indicating whether the dep is a genrule that produces .proto files
134func protoFromGenPartitionMapper(pathCtx android.BazelConversionContext) bazel.LabelMapper {
135 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
136 mod, exists := ctx.ModuleFromName(label.OriginalModuleName)
137 if !exists {
138 return label.Label, false
139 }
140 gen, isGen := mod.(*genrule.Module)
141 if !isGen {
142 return label.Label, false
143 }
144 if containsProto(ctx, gen.RawOutputFiles(pathCtx)) {
145 // Return unmodified label + true
146 // True will ensure that this module gets dropped from `srcs` of the generated cc_* target. `srcs` is reserved for .cpp files
147 return label.Label, true
148 }
149 return label.Label, false
150 }
151}
152
153// Returns true if srcs contains only .proto files
154// Raises an exception if there is a combination of .proto and non .proto srcs
155func containsProto(ctx bazel.OtherModuleContext, srcs []string) bool {
156 onlyProtos := false
157 for _, src := range srcs {
158 if strings.HasSuffix(src, ".proto") {
159 onlyProtos = true
160 } else if onlyProtos {
161 // This is not a proto file, and we have encountered a .proto file previously
162 ctx.ModuleErrorf("TOOD: Add bp2build support combination of .proto and non .proto files in outs of genrule")
163 }
164 }
165 return onlyProtos
166}
167
Sam Delmericoc7681022022-02-04 21:01:20 +0000168// groupSrcsByExtension partitions `srcs` into groups based on file extension.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000169func groupSrcsByExtension(ctx android.BazelConversionPathContext, srcs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400170 // Convert filegroup dependencies into extension-specific filegroups filtered in the filegroup.bzl
171 // macro.
172 addSuffixForFilegroup := func(suffix string) bazel.LabelMapper {
Vinh Tran9f6796a2022-08-16 13:10:31 -0400173 return func(otherModuleCtx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
174
175 m, exists := otherModuleCtx.ModuleFromName(label.OriginalModuleName)
Liz Kammer12615db2021-09-28 09:19:17 -0400176 labelStr := label.Label
Vinh Tran9f6796a2022-08-16 13:10:31 -0400177 if !exists || !android.IsFilegroup(otherModuleCtx, m) {
178 return labelStr, false
179 }
Yu Liu2aa806b2022-09-01 11:54:47 -0700180 // If the filegroup is already converted to aidl_library or proto_library,
181 // skip creating _c_srcs, _as_srcs, _cpp_srcs filegroups
182 fg, _ := m.(android.FileGroupAsLibrary)
183 if fg.ShouldConvertToAidlLibrary(ctx) || fg.ShouldConvertToProtoLibrary(ctx) {
Liz Kammer12615db2021-09-28 09:19:17 -0400184 return labelStr, false
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000185 }
Liz Kammer12615db2021-09-28 09:19:17 -0400186 return labelStr + suffix, true
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400187 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000188 }
189
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400190 // TODO(b/190006308): Handle language detection of sources in a Bazel rule.
Sam Delmericoc7681022022-02-04 21:01:20 +0000191 labels := bazel.LabelPartitions{
192 protoSrcPartition: android.ProtoSrcLabelPartition,
Liz Kammeraabfb5d2021-12-08 15:25:06 -0500193 cSrcPartition: bazel.LabelPartition{Extensions: []string{".c"}, LabelMapper: addSuffixForFilegroup("_c_srcs")},
194 asSrcPartition: bazel.LabelPartition{Extensions: []string{".s", ".S"}, LabelMapper: addSuffixForFilegroup("_as_srcs")},
Cole Faust7071a052022-07-29 15:58:33 -0700195 asmSrcPartition: bazel.LabelPartition{Extensions: []string{".asm"}},
Vinh Tran9f6796a2022-08-16 13:10:31 -0400196 aidlSrcPartition: android.AidlSrcLabelPartition,
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000197 // TODO(http://b/231968910): If there is ever a filegroup target that
198 // contains .l or .ll files we will need to find a way to add a
199 // LabelMapper for these that identifies these filegroups and
200 // converts them appropriately
Spandan Dasa99348d2023-08-01 23:10:05 +0000201 lSrcPartition: bazel.LabelPartition{Extensions: []string{".l"}},
202 llSrcPartition: bazel.LabelPartition{Extensions: []string{".ll"}},
203 rScriptSrcPartition: bazel.LabelPartition{Extensions: []string{".fs", ".rscript"}},
204 xsdSrcPartition: bazel.LabelPartition{LabelMapper: android.XsdLabelMapper(xsdConfigCppTarget)},
205 protoFromGenPartition: bazel.LabelPartition{LabelMapper: protoFromGenPartitionMapper(ctx)},
Liz Kammer57e2e7a2021-09-20 12:55:02 -0400206 // C++ is the "catch-all" group, and comprises generated sources because we don't
207 // know the language of these sources until the genrule is executed.
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000208 cppSrcPartition: bazel.LabelPartition{Extensions: []string{".cpp", ".cc", ".cxx", ".mm"}, LabelMapper: addSuffixForFilegroup("_cpp_srcs"), Keep_remainder: true},
209 syspropSrcPartition: bazel.LabelPartition{Extensions: []string{".sysprop"}},
Spandan Dasdf4c2132023-05-09 23:58:52 +0000210 yaccSrcPartition: bazel.LabelPartition{Extensions: []string{".y", "yy"}},
Sam Delmericoc7681022022-02-04 21:01:20 +0000211 }
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000212
Sam Delmericoc7681022022-02-04 21:01:20 +0000213 return bazel.PartitionLabelListAttribute(ctx, &srcs, labels)
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000214}
215
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400216func partitionHeaders(ctx android.BazelConversionPathContext, hdrs bazel.LabelListAttribute) bazel.PartitionToLabelListAttribute {
217 labels := bazel.LabelPartitions{
Liz Kammer0db0e342023-07-18 11:39:30 -0400218 xsdSrcPartition: bazel.LabelPartition{LabelMapper: android.XsdLabelMapper(xsdConfigCppTarget)},
219 genrulePartition: bazel.LabelPartition{LabelMapper: genrule.GenruleCcHeaderLabelMapper},
220 hdrPartition: bazel.LabelPartition{Keep_remainder: true},
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400221 }
222 return bazel.PartitionLabelListAttribute(ctx, &hdrs, labels)
223}
224
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000225// bp2BuildParseLibProps returns the attributes for a variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000226func bp2BuildParseLibProps(ctx android.BazelConversionPathContext, module *Module, isStatic bool) staticOrSharedAttributes {
Jingwen Chen53681ef2021-04-29 08:15:13 +0000227 lib, ok := module.compiler.(*libraryDecorator)
228 if !ok {
Liz Kammer2222c6b2021-05-24 15:41:47 -0400229 return staticOrSharedAttributes{}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000230 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000231 return bp2buildParseStaticOrSharedProps(ctx, module, lib, isStatic)
232}
Jingwen Chen53681ef2021-04-29 08:15:13 +0000233
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000234// bp2buildParseSharedProps returns the attributes for the shared variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000235func bp2BuildParseSharedProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000236 return bp2BuildParseLibProps(ctx, module, false)
Jingwen Chen53681ef2021-04-29 08:15:13 +0000237}
238
239// bp2buildParseStaticProps returns the attributes for the static variant of a cc_library.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000240func bp2BuildParseStaticProps(ctx android.BazelConversionPathContext, module *Module) staticOrSharedAttributes {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000241 return bp2BuildParseLibProps(ctx, module, true)
Liz Kammer2222c6b2021-05-24 15:41:47 -0400242}
243
Liz Kammer7a210ac2021-09-22 15:52:58 -0400244type depsPartition struct {
245 export bazel.LabelList
246 implementation bazel.LabelList
247}
248
Jingwen Chen55bc8202021-11-02 06:40:51 +0000249type bazelLabelForDepsFn func(android.BazelConversionPathContext, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400250
Jingwen Chen55bc8202021-11-02 06:40:51 +0000251func maybePartitionExportedAndImplementationsDeps(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, exportedDeps []string, fn bazelLabelForDepsFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400252 if !exportsDeps {
253 return depsPartition{
254 implementation: fn(ctx, allDeps),
255 }
256 }
257
Liz Kammer7a210ac2021-09-22 15:52:58 -0400258 implementation, export := android.FilterList(allDeps, exportedDeps)
259
260 return depsPartition{
261 export: fn(ctx, export),
262 implementation: fn(ctx, implementation),
263 }
264}
265
Jingwen Chen55bc8202021-11-02 06:40:51 +0000266type bazelLabelForDepsExcludesFn func(android.BazelConversionPathContext, []string, []string) bazel.LabelList
Liz Kammer7a210ac2021-09-22 15:52:58 -0400267
Jingwen Chen55bc8202021-11-02 06:40:51 +0000268func maybePartitionExportedAndImplementationsDepsExcludes(ctx android.BazelConversionPathContext, exportsDeps bool, allDeps, excludes, exportedDeps []string, fn bazelLabelForDepsExcludesFn) depsPartition {
Liz Kammer2b8004b2021-10-04 13:55:44 -0400269 if !exportsDeps {
270 return depsPartition{
271 implementation: fn(ctx, allDeps, excludes),
272 }
273 }
Liz Kammer7a210ac2021-09-22 15:52:58 -0400274 implementation, export := android.FilterList(allDeps, exportedDeps)
275
276 return depsPartition{
277 export: fn(ctx, export, excludes),
278 implementation: fn(ctx, implementation, excludes),
279 }
280}
281
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000282func bp2BuildPropParseHelper(ctx android.ArchVariantContext, module *Module, propsType interface{}, parseFunc func(axis bazel.ConfigurationAxis, config string, props interface{})) {
283 for axis, configToProps := range module.GetArchVariantProperties(ctx, propsType) {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800284 for cfg, props := range configToProps {
285 parseFunc(axis, cfg, props)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000286 }
287 }
288}
289
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000290// Parses properties common to static and shared libraries. Also used for prebuilt libraries.
Liz Kammeraceec252023-03-24 09:46:36 -0400291func bp2buildParseStaticOrSharedProps(ctx android.BazelConversionPathContext, module *Module, lib *libraryDecorator, isStatic bool) staticOrSharedAttributes {
Liz Kammer135bf552021-08-11 10:46:06 -0400292 attrs := staticOrSharedAttributes{}
Jingwen Chenbcf53042021-05-26 04:42:42 +0000293
Liz Kammer9abd62d2021-05-21 08:37:59 -0400294 setAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000295 attrs.Copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutHiddenVisibility))
Jingwen Chenc4dc9b42021-06-11 12:51:48 +0000296 attrs.Srcs.SetSelectValue(axis, config, android.BazelLabelForModuleSrc(ctx, props.Srcs))
Chris Parsons953b3562021-09-20 15:14:39 -0400297 attrs.System_dynamic_deps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, props.System_shared_libs))
Liz Kammer7a210ac2021-09-22 15:52:58 -0400298
Liz Kammer2b8004b2021-10-04 13:55:44 -0400299 staticDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Static_libs, props.Export_static_lib_headers, bazelLabelForStaticDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400300 attrs.Deps.SetSelectValue(axis, config, staticDeps.export)
301 attrs.Implementation_deps.SetSelectValue(axis, config, staticDeps.implementation)
302
Liz Kammer2b8004b2021-10-04 13:55:44 -0400303 sharedDeps := maybePartitionExportedAndImplementationsDeps(ctx, true, props.Shared_libs, props.Export_shared_lib_headers, bazelLabelForSharedDeps)
Liz Kammer7a210ac2021-09-22 15:52:58 -0400304 attrs.Dynamic_deps.SetSelectValue(axis, config, sharedDeps.export)
305 attrs.Implementation_dynamic_deps.SetSelectValue(axis, config, sharedDeps.implementation)
306
307 attrs.Whole_archive_deps.SetSelectValue(axis, config, bazelLabelForWholeDeps(ctx, props.Whole_static_libs))
Chris Parsons58852a02021-12-09 18:10:18 -0500308 attrs.Enabled.SetSelectValue(axis, config, props.Enabled)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000309 }
Liz Kammer135bf552021-08-11 10:46:06 -0400310 // system_dynamic_deps distinguishes between nil/empty list behavior:
311 // nil -> use default values
312 // empty list -> no values specified
313 attrs.System_dynamic_deps.ForceSpecifyEmptyList = true
Jingwen Chenbcf53042021-05-26 04:42:42 +0000314
Liz Kammeraceec252023-03-24 09:46:36 -0400315 var apexAvailable []string
Jingwen Chenbcf53042021-05-26 04:42:42 +0000316 if isStatic {
Liz Kammeraceec252023-03-24 09:46:36 -0400317 apexAvailable = lib.StaticProperties.Static.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000318 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
319 if staticOrSharedProps, ok := props.(*StaticProperties); ok {
320 setAttrs(axis, config, staticOrSharedProps.Static)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000321 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000322 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000323 } else {
Liz Kammeraceec252023-03-24 09:46:36 -0400324 apexAvailable = lib.SharedProperties.Shared.Apex_available
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000325 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
326 if staticOrSharedProps, ok := props.(*SharedProperties); ok {
327 setAttrs(axis, config, staticOrSharedProps.Shared)
Jingwen Chenbcf53042021-05-26 04:42:42 +0000328 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000329 })
Jingwen Chenbcf53042021-05-26 04:42:42 +0000330 }
331
Liz Kammerae3994e2021-10-19 09:45:48 -0400332 partitionedSrcs := groupSrcsByExtension(ctx, attrs.Srcs)
333 attrs.Srcs = partitionedSrcs[cppSrcPartition]
334 attrs.Srcs_c = partitionedSrcs[cSrcPartition]
335 attrs.Srcs_as = partitionedSrcs[asSrcPartition]
Jingwen Chen14a8bda2021-06-02 11:10:02 +0000336
Spandan Das39b6cc52023-04-12 19:05:49 +0000337 attrs.Apex_available = android.ConvertApexAvailableToTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), apexAvailable)
Liz Kammeraceec252023-03-24 09:46:36 -0400338
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000339 attrs.Features.Append(convertHiddenVisibilityToFeatureStaticOrShared(ctx, module, isStatic))
340
Liz Kammer12615db2021-09-28 09:19:17 -0400341 if !partitionedSrcs[protoSrcPartition].IsEmpty() {
342 // TODO(b/208815215): determine whether this is used and add support if necessary
343 ctx.ModuleErrorf("Migrating static/shared only proto srcs is not currently supported")
344 }
345
Jingwen Chenbcf53042021-05-26 04:42:42 +0000346 return attrs
Jingwen Chen53681ef2021-04-29 08:15:13 +0000347}
348
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400349// Convenience struct to hold all attributes parsed from prebuilt properties.
350type prebuiltAttributes struct {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000351 Src bazel.LabelAttribute
352 Enabled bazel.BoolAttribute
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400353}
354
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000355func parseSrc(ctx android.BazelConversionPathContext, srcLabelAttribute *bazel.LabelAttribute, axis bazel.ConfigurationAxis, config string, srcs []string) {
356 srcFileError := func() {
357 ctx.ModuleErrorf("parseSrc: Expected at most one source file for %s %s\n", axis, config)
358 }
359 if len(srcs) > 1 {
360 srcFileError()
361 return
362 } else if len(srcs) == 0 {
363 return
364 }
365 if srcLabelAttribute.SelectValue(axis, config) != nil {
366 srcFileError()
367 return
368 }
369 srcLabelAttribute.SetSelectValue(axis, config, android.BazelLabelForModuleSrcSingle(ctx, srcs[0]))
370}
371
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxac5097f2021-09-01 21:22:09 +0000372// NOTE: Used outside of Soong repo project, in the clangprebuilts.go bootstrap_go_package
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000373func 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 +0000374
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400375 var srcLabelAttribute bazel.LabelAttribute
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000376 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
377 if prebuiltLinkerProperties, ok := props.(*prebuiltLinkerProperties); ok {
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000378 parseSrc(ctx, &srcLabelAttribute, axis, config, prebuiltLinkerProperties.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000379 }
380 })
381
382 var enabledLabelAttribute bazel.BoolAttribute
383 parseAttrs := func(axis bazel.ConfigurationAxis, config string, props StaticOrSharedProperties) {
384 if props.Enabled != nil {
385 enabledLabelAttribute.SetSelectValue(axis, config, props.Enabled)
386 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000387 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000388 }
389
390 if isStatic {
391 bp2BuildPropParseHelper(ctx, module, &StaticProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
392 if staticProperties, ok := props.(*StaticProperties); ok {
393 parseAttrs(axis, config, staticProperties.Static)
394 }
395 })
396 } else {
397 bp2BuildPropParseHelper(ctx, module, &SharedProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
398 if sharedProperties, ok := props.(*SharedProperties); ok {
399 parseAttrs(axis, config, sharedProperties.Shared)
400 }
401 })
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400402 }
403
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400404 return prebuiltAttributes{
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000405 Src: srcLabelAttribute,
406 Enabled: enabledLabelAttribute,
407 }
408}
409
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000410func bp2BuildParsePrebuiltBinaryProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
411 var srcLabelAttribute bazel.LabelAttribute
412 bp2BuildPropParseHelper(ctx, module, &prebuiltLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
413 if props, ok := props.(*prebuiltLinkerProperties); ok {
414 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
Trevor Radcliffe58ea4512022-04-07 20:36:39 +0000415 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxb12ff592022-09-01 15:04:04 +0000416 })
417
418 return prebuiltAttributes{
419 Src: srcLabelAttribute,
Rupert Shuttleworthffd45822021-05-14 03:02:34 -0400420 }
421}
422
Colin Crossc5075e92022-12-05 16:46:39 -0800423func bp2BuildParsePrebuiltObjectProps(ctx android.BazelConversionPathContext, module *Module) prebuiltAttributes {
424 var srcLabelAttribute bazel.LabelAttribute
425 bp2BuildPropParseHelper(ctx, module, &prebuiltObjectProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
426 if props, ok := props.(*prebuiltObjectProperties); ok {
427 parseSrc(ctx, &srcLabelAttribute, axis, config, props.Srcs)
428 }
429 })
430
431 return prebuiltAttributes{
432 Src: srcLabelAttribute,
433 }
434}
435
Liz Kammere6583482021-10-19 13:56:10 -0400436type baseAttributes struct {
437 compilerAttributes
438 linkerAttributes
Liz Kammer12615db2021-09-28 09:19:17 -0400439
Trevor Radcliffedb7e0262022-10-28 16:48:18 +0000440 // A combination of compilerAttributes.features and linkerAttributes.features, as well as sanitizer features
Cole Faust5fa4e962022-08-22 14:31:04 -0700441 features bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400442 protoDependency *bazel.LabelAttribute
Vinh Tran9f6796a2022-08-16 13:10:31 -0400443 aidlDependency *bazel.LabelAttribute
Yu Liuf01a0f02022-12-07 15:45:30 -0800444 Native_coverage *bool
Liz Kammere6583482021-10-19 13:56:10 -0400445}
446
Jingwen Chen107c0de2021-04-09 10:43:12 +0000447// Convenience struct to hold all attributes parsed from compiler properties.
448type compilerAttributes struct {
Chris Parsons990c4f42021-05-25 12:10:58 -0400449 // Options for all languages
450 copts bazel.StringListAttribute
451 // Assembly options and sources
452 asFlags bazel.StringListAttribute
453 asSrcs bazel.LabelListAttribute
Cole Faust7071a052022-07-29 15:58:33 -0700454 asmSrcs bazel.LabelListAttribute
Chris Parsons990c4f42021-05-25 12:10:58 -0400455 // C options and sources
456 conlyFlags bazel.StringListAttribute
457 cSrcs bazel.LabelListAttribute
458 // C++ options and sources
459 cppFlags bazel.StringListAttribute
Jingwen Chened9c17d2021-04-13 07:14:55 +0000460 srcs bazel.LabelListAttribute
Chris Parsons2c788392021-08-10 11:58:07 -0400461
Liz Kammer084d6a92023-06-22 16:23:53 -0400462 // xsd config sources
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400463 xsdSrcs bazel.LabelListAttribute
464 exportXsdSrcs bazel.LabelListAttribute
Liz Kammer084d6a92023-06-22 16:23:53 -0400465
Liz Kammer0db0e342023-07-18 11:39:30 -0400466 // genrule headers
467 genruleHeaders bazel.LabelListAttribute
468 exportGenruleHeaders bazel.LabelListAttribute
469
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000470 // Lex sources and options
471 lSrcs bazel.LabelListAttribute
472 llSrcs bazel.LabelListAttribute
473 lexopts bazel.StringListAttribute
474
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000475 // Sysprop sources
476 syspropSrcs bazel.LabelListAttribute
477
Spandan Dasdf4c2132023-05-09 23:58:52 +0000478 // Yacc sources
479 yaccSrc *bazel.LabelAttribute
480 yaccFlags bazel.StringListAttribute
481 yaccGenLocationHeader bazel.BoolAttribute
482 yaccGenPositionHeader bazel.BoolAttribute
483
Alixe2667872023-04-24 14:57:32 +0000484 rsSrcs bazel.LabelListAttribute
485
Liz Kammere6583482021-10-19 13:56:10 -0400486 hdrs bazel.LabelListAttribute
487
Chris Parsons2c788392021-08-10 11:58:07 -0400488 rtti bazel.BoolAttribute
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000489
490 // Not affected by arch variants
491 stl *string
Chris Parsons79bd2b72021-11-29 17:52:41 -0500492 cStd *string
Jingwen Chen5b11ab12021-10-11 17:44:33 +0000493 cppStd *string
Liz Kammer35687bc2021-09-10 10:07:07 -0400494
495 localIncludes bazel.StringListAttribute
496 absoluteIncludes bazel.StringListAttribute
Liz Kammer12615db2021-09-28 09:19:17 -0400497
Liz Kammer1263d9b2021-12-10 14:28:20 -0500498 includes BazelIncludes
499
Alixe2667872023-04-24 14:57:32 +0000500 protoSrcs bazel.LabelListAttribute
501 aidlSrcs bazel.LabelListAttribute
502 rscriptSrcs bazel.LabelListAttribute
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000503
504 stubsSymbolFile *string
505 stubsVersions bazel.StringListAttribute
Cole Faust5fa4e962022-08-22 14:31:04 -0700506
507 features bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500508
Spandan Das39ccf932023-05-26 18:03:39 +0000509 stem bazel.StringAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500510 suffix bazel.StringAttribute
Vinh Tran99270ea2022-11-28 11:15:23 -0500511
512 fdoProfile bazel.LabelAttribute
Trevor Radcliffed9b7f172023-08-09 22:21:38 +0000513
514 additionalCompilerInputs bazel.LabelListAttribute
Jingwen Chen107c0de2021-04-09 10:43:12 +0000515}
516
Liz Kammercac7f692021-12-16 14:19:32 -0500517type filterOutFn func(string) bool
518
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000519// filterOutHiddenVisibility removes the flag specifying hidden visibility as
520// this flag is converted to a toolchain feature
521func filterOutHiddenVisibility(flag string) bool {
522 return flag == config.VisibilityHiddenFlag
523}
524
Liz Kammercac7f692021-12-16 14:19:32 -0500525func filterOutStdFlag(flag string) bool {
526 return strings.HasPrefix(flag, "-std=")
527}
528
Alix1be00d42022-05-16 22:56:04 +0000529func filterOutClangUnknownCflags(flag string) bool {
530 for _, f := range config.ClangUnknownCflags {
531 if f == flag {
532 return true
533 }
534 }
535 return false
536}
537
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000538func parseCommandLineFlags(soongFlags []string, filterOut ...filterOutFn) []string {
Liz Kammere6583482021-10-19 13:56:10 -0400539 var result []string
540 for _, flag := range soongFlags {
Alix1be00d42022-05-16 22:56:04 +0000541 skipFlag := false
542 for _, filter := range filterOut {
543 if filter != nil && filter(flag) {
544 skipFlag = true
545 }
546 }
547 if skipFlag {
Liz Kammercac7f692021-12-16 14:19:32 -0500548 continue
549 }
Liz Kammere6583482021-10-19 13:56:10 -0400550 // Soong's cflags can contain spaces, like `-include header.h`. For
551 // Bazel's copts, split them up to be compatible with the
552 // no_copts_tokenization feature.
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000553 result = append(result, strings.Split(flag, " ")...)
Liz Kammere6583482021-10-19 13:56:10 -0400554 }
555 return result
556}
Jingwen Chened9c17d2021-04-13 07:14:55 +0000557
Jingwen Chen55bc8202021-11-02 06:40:51 +0000558func (ca *compilerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis, config string, props *BaseCompilerProperties) {
Liz Kammere6583482021-10-19 13:56:10 -0400559 // If there's arch specific srcs or exclude_srcs, generate a select entry for it.
560 // TODO(b/186153868): do this for OS specific srcs and exclude_srcs too.
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400561 srcsList, ok := parseSrcs(ctx, props)
Liz Kammer084d6a92023-06-22 16:23:53 -0400562
563 if ok {
Liz Kammere6583482021-10-19 13:56:10 -0400564 ca.srcs.SetSelectValue(axis, config, srcsList)
Chris Parsons990c4f42021-05-25 12:10:58 -0400565 }
566
Liz Kammere6583482021-10-19 13:56:10 -0400567 localIncludeDirs := props.Local_include_dirs
568 if axis == bazel.NoConfigAxis {
Chris Parsons79bd2b72021-11-29 17:52:41 -0500569 ca.cStd, ca.cppStd = bp2buildResolveCppStdValue(props.C_std, props.Cpp_std, props.Gnu_extensions)
Liz Kammere6583482021-10-19 13:56:10 -0400570 if includeBuildDirectory(props.Include_build_directory) {
571 localIncludeDirs = append(localIncludeDirs, ".")
Liz Kammer222bdcf2021-10-11 14:15:51 -0400572 }
Jingwen Chene32e9e02021-04-23 09:17:24 +0000573 }
574
Liz Kammere6583482021-10-19 13:56:10 -0400575 ca.absoluteIncludes.SetSelectValue(axis, config, props.Include_dirs)
576 ca.localIncludes.SetSelectValue(axis, config, localIncludeDirs)
577
Cole Faust5fa4e962022-08-22 14:31:04 -0700578 instructionSet := proptools.StringDefault(props.Instruction_set, "")
579 if instructionSet == "arm" {
Trevor Radcliffe5f0c2ac2023-05-15 18:00:59 +0000580 ca.features.SetSelectValue(axis, config, []string{"arm_isa_arm"})
Cole Faust5fa4e962022-08-22 14:31:04 -0700581 } else if instructionSet != "" && instructionSet != "thumb" {
582 ctx.ModuleErrorf("Unknown value for instruction_set: %s", instructionSet)
583 }
584
Liz Kammercac7f692021-12-16 14:19:32 -0500585 // In Soong, cflags occur on the command line before -std=<val> flag, resulting in the value being
586 // overridden. In Bazel we always allow overriding, via flags; however, this can cause
587 // incompatibilities, so we remove "-std=" flags from Cflag properties while leaving it in other
588 // cases.
Trevor Radcliffea8b44162023-04-14 18:25:24 +0000589 ca.copts.SetSelectValue(axis, config, parseCommandLineFlags(props.Cflags, filterOutStdFlag, filterOutClangUnknownCflags, filterOutHiddenVisibility))
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +0000590 ca.asFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Asflags, nil))
591 ca.conlyFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Conlyflags, filterOutClangUnknownCflags))
592 ca.cppFlags.SetSelectValue(axis, config, parseCommandLineFlags(props.Cppflags, filterOutClangUnknownCflags))
Liz Kammere6583482021-10-19 13:56:10 -0400593 ca.rtti.SetSelectValue(axis, config, props.Rtti)
594}
595
Jingwen Chen55bc8202021-11-02 06:40:51 +0000596func (ca *compilerAttributes) convertStlProps(ctx android.ArchVariantContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000597 bp2BuildPropParseHelper(ctx, module, &StlProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
598 if stlProps, ok := props.(*StlProperties); ok {
599 if stlProps.Stl == nil {
600 return
601 }
602 if ca.stl == nil {
Liz Kammer7128d382022-05-12 11:42:33 -0400603 stl := deduplicateStlInput(*stlProps.Stl)
604 ca.stl = &stl
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000605 } else if ca.stl != stlProps.Stl {
606 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 -0400607 }
Jingwen Chenc1c26502021-04-05 10:35:13 +0000608 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +0000609 })
Liz Kammere6583482021-10-19 13:56:10 -0400610}
Jingwen Chenc1c26502021-04-05 10:35:13 +0000611
Jingwen Chen55bc8202021-11-02 06:40:51 +0000612func (ca *compilerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Liz Kammerba7a9c52021-05-26 08:45:30 -0400613 productVarPropNameToAttribute := map[string]*bazel.StringListAttribute{
Liz Kammere6583482021-10-19 13:56:10 -0400614 "Cflags": &ca.copts,
615 "Asflags": &ca.asFlags,
Yu Liu93893ba2023-05-01 13:49:52 -0700616 "Cppflags": &ca.cppFlags,
Liz Kammerba7a9c52021-05-26 08:45:30 -0400617 }
Liz Kammerba7a9c52021-05-26 08:45:30 -0400618 for propName, attr := range productVarPropNameToAttribute {
Jingwen Chen25825ca2021-11-15 12:28:43 +0000619 if productConfigProps, exists := productVariableProps[propName]; exists {
620 for productConfigProp, prop := range productConfigProps {
621 flags, ok := prop.([]string)
Liz Kammerba7a9c52021-05-26 08:45:30 -0400622 if !ok {
623 ctx.ModuleErrorf("Could not convert product variable %s property", proptools.PropertyNameForField(propName))
624 }
Cole Faust150f9a52023-04-26 10:52:24 -0700625 newFlags, _ := bazel.TryVariableSubstitutions(flags, productConfigProp.Name())
Jingwen Chen25825ca2021-11-15 12:28:43 +0000626 attr.SetSelectValue(productConfigProp.ConfigurationAxis(), productConfigProp.SelectKey(), newFlags)
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400627 }
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400628 }
629 }
Liz Kammere6583482021-10-19 13:56:10 -0400630}
Liz Kammer6fd7b3f2021-05-06 13:54:29 -0400631
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400632func (ca *compilerAttributes) finalize(ctx android.BazelConversionPathContext, implementationHdrs, exportHdrs bazel.LabelListAttribute) {
Liz Kammere6583482021-10-19 13:56:10 -0400633 ca.srcs.ResolveExcludes()
634 partitionedSrcs := groupSrcsByExtension(ctx, ca.srcs)
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400635 partitionedImplHdrs := partitionHeaders(ctx, implementationHdrs)
636 partitionedHdrs := partitionHeaders(ctx, exportHdrs)
Liz Kammere6583482021-10-19 13:56:10 -0400637
Liz Kammer12615db2021-09-28 09:19:17 -0400638 ca.protoSrcs = partitionedSrcs[protoSrcPartition]
Spandan Dasa99348d2023-08-01 23:10:05 +0000639 ca.protoSrcs.Append(partitionedSrcs[protoFromGenPartition])
Vinh Tran9f6796a2022-08-16 13:10:31 -0400640 ca.aidlSrcs = partitionedSrcs[aidlSrcPartition]
Liz Kammer12615db2021-09-28 09:19:17 -0400641
Liz Kammere6583482021-10-19 13:56:10 -0400642 for p, lla := range partitionedSrcs {
643 // if there are no sources, there is no need for headers
644 if lla.IsEmpty() {
645 continue
646 }
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400647 lla.Append(partitionedImplHdrs[hdrPartition])
Liz Kammere6583482021-10-19 13:56:10 -0400648 partitionedSrcs[p] = lla
649 }
650
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400651 ca.hdrs = partitionedHdrs[hdrPartition]
652
653 ca.includesFromHeaders(ctx, partitionedImplHdrs[hdrPartition], partitionedHdrs[hdrPartition])
654
655 xsdSrcs := bazel.SubtractBazelLabelListAttribute(partitionedSrcs[xsdSrcPartition], partitionedHdrs[xsdSrcPartition])
656 xsdSrcs.Append(partitionedImplHdrs[xsdSrcPartition])
657 ca.exportXsdSrcs = partitionedHdrs[xsdSrcPartition]
658 ca.xsdSrcs = bazel.FirstUniqueBazelLabelListAttribute(xsdSrcs)
659
Liz Kammer0db0e342023-07-18 11:39:30 -0400660 ca.genruleHeaders = partitionedImplHdrs[genrulePartition]
661 ca.exportGenruleHeaders = partitionedHdrs[genrulePartition]
662
Liz Kammere6583482021-10-19 13:56:10 -0400663 ca.srcs = partitionedSrcs[cppSrcPartition]
664 ca.cSrcs = partitionedSrcs[cSrcPartition]
665 ca.asSrcs = partitionedSrcs[asSrcPartition]
Cole Faust7071a052022-07-29 15:58:33 -0700666 ca.asmSrcs = partitionedSrcs[asmSrcPartition]
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000667 ca.lSrcs = partitionedSrcs[lSrcPartition]
668 ca.llSrcs = partitionedSrcs[llSrcPartition]
Spandan Dasdf4c2132023-05-09 23:58:52 +0000669 if yacc := partitionedSrcs[yaccSrcPartition]; !yacc.IsEmpty() {
670 if len(yacc.Value.Includes) > 1 {
671 ctx.PropertyErrorf("srcs", "Found multiple yacc (.y/.yy) files in library")
672 }
673 ca.yaccSrc = bazel.MakeLabelAttribute(yacc.Value.Includes[0].Label)
674 }
Trevor Radcliffecee4e052022-09-06 19:31:25 +0000675 ca.syspropSrcs = partitionedSrcs[syspropSrcPartition]
Alixe2667872023-04-24 14:57:32 +0000676 ca.rscriptSrcs = partitionedSrcs[rScriptSrcPartition]
Liz Kammere6583482021-10-19 13:56:10 -0400677
678 ca.absoluteIncludes.DeduplicateAxesFromBase()
679 ca.localIncludes.DeduplicateAxesFromBase()
680}
681
682// Parse srcs from an arch or OS's props value.
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400683func parseSrcs(ctx android.BazelConversionPathContext, props *BaseCompilerProperties) (bazel.LabelList, bool) {
Liz Kammere6583482021-10-19 13:56:10 -0400684 anySrcs := false
685 // Add srcs-like dependencies such as generated files.
686 // First create a LabelList containing these dependencies, then merge the values with srcs.
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400687 genSrcs := props.Generated_sources
Spandan Das922171d2023-05-31 23:32:40 +0000688 generatedSrcsLabelList := android.BazelLabelForModuleDepsExcludes(ctx, genSrcs, props.Exclude_generated_sources)
Liz Kammere6583482021-10-19 13:56:10 -0400689 if len(props.Generated_sources) > 0 || len(props.Exclude_generated_sources) > 0 {
690 anySrcs = true
691 }
692
693 allSrcsLabelList := android.BazelLabelForModuleSrcExcludes(ctx, props.Srcs, props.Exclude_srcs)
Vinh Tran9f6796a2022-08-16 13:10:31 -0400694
Liz Kammere6583482021-10-19 13:56:10 -0400695 if len(props.Srcs) > 0 || len(props.Exclude_srcs) > 0 {
696 anySrcs = true
697 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400698
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400699 return bazel.AppendBazelLabelLists(allSrcsLabelList, generatedSrcsLabelList), anySrcs
Liz Kammere6583482021-10-19 13:56:10 -0400700}
701
Liz Kammera5a29de2022-05-25 23:19:37 -0400702func bp2buildStdVal(std *string, prefix string, useGnu bool) *string {
703 defaultVal := prefix + "_std_default"
Chris Parsons79bd2b72021-11-29 17:52:41 -0500704 // If c{,pp}std properties are not specified, don't generate them in the BUILD file.
705 // Defaults are handled by the toolchain definition.
706 // However, if gnu_extensions is false, then the default gnu-to-c version must be specified.
Liz Kammera5a29de2022-05-25 23:19:37 -0400707 stdVal := proptools.StringDefault(std, defaultVal)
708 if stdVal == "experimental" || stdVal == defaultVal {
709 if stdVal == "experimental" {
710 stdVal = prefix + "_std_experimental"
711 }
712 if !useGnu {
713 stdVal += "_no_gnu"
714 }
715 } else if !useGnu {
716 stdVal = gnuToCReplacer.Replace(stdVal)
Chris Parsons79bd2b72021-11-29 17:52:41 -0500717 }
718
Liz Kammera5a29de2022-05-25 23:19:37 -0400719 if stdVal == defaultVal {
720 return nil
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500721 }
Liz Kammera5a29de2022-05-25 23:19:37 -0400722 return &stdVal
723}
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500724
Liz Kammera5a29de2022-05-25 23:19:37 -0400725func bp2buildResolveCppStdValue(c_std *string, cpp_std *string, gnu_extensions *bool) (*string, *string) {
726 useGnu := useGnuExtensions(gnu_extensions)
727
728 return bp2buildStdVal(c_std, "c", useGnu), bp2buildStdVal(cpp_std, "cpp", useGnu)
Liz Kammere6583482021-10-19 13:56:10 -0400729}
730
Liz Kammer1263d9b2021-12-10 14:28:20 -0500731// packageFromLabel extracts package from a fully-qualified or relative Label and whether the label
732// is fully-qualified.
733// e.g. fully-qualified "//a/b:foo" -> "a/b", true, relative: ":bar" -> ".", false
734func packageFromLabel(label string) (string, bool) {
735 split := strings.Split(label, ":")
736 if len(split) != 2 {
737 return "", false
738 }
739 if split[0] == "" {
740 return ".", false
741 }
742 // remove leading "//"
743 return split[0][2:], true
744}
745
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400746// includesFromHeaders gets the include directories needed from generated headers
747func (ca *compilerAttributes) includesFromHeaders(ctx android.BazelConversionPathContext, implHdrs, hdrs bazel.LabelListAttribute) {
748 local, absolute := includesFromLabelListAttribute(implHdrs, ca.localIncludes, ca.absoluteIncludes)
749 localExport, absoluteExport := includesFromLabelListAttribute(hdrs, ca.includes.Includes, ca.includes.AbsoluteIncludes)
750
751 ca.localIncludes = local
752 ca.absoluteIncludes = absolute
753
754 ca.includes.Includes = localExport
755 ca.includes.AbsoluteIncludes = absoluteExport
756}
757
758// includesFromLabelList extracts the packages from a LabelListAttribute that should be includes and
759// combines them with existing local/absolute includes.
760func includesFromLabelListAttribute(attr bazel.LabelListAttribute, existingLocal, existingAbsolute bazel.StringListAttribute) (bazel.StringListAttribute, bazel.StringListAttribute) {
761 localAttr := existingLocal.Clone()
762 absoluteAttr := existingAbsolute.Clone()
763 if !attr.Value.IsEmpty() {
764 l, a := includesFromLabelList(attr.Value, existingLocal.Value, existingAbsolute.Value)
765 localAttr.SetSelectValue(bazel.NoConfigAxis, "", l)
766 absoluteAttr.SetSelectValue(bazel.NoConfigAxis, "", a)
767 }
768 for axis, configToLabels := range attr.ConfigurableValues {
769 for c, labels := range configToLabels {
770 local := existingLocal.SelectValue(axis, c)
771 absolute := existingAbsolute.SelectValue(axis, c)
772 l, a := includesFromLabelList(labels, local, absolute)
773 localAttr.SetSelectValue(axis, c, l)
774 absoluteAttr.SetSelectValue(axis, c, a)
775 }
776 }
777 return *localAttr, *absoluteAttr
778}
779
780// includesFromLabelList extracts relative/absolute includes from a bazel.LabelList.
781func includesFromLabelList(labelList bazel.LabelList, existingRel, existingAbs []string) ([]string, []string) {
782 var relative, absolute []string
Liz Kammer1263d9b2021-12-10 14:28:20 -0500783 for _, hdr := range labelList.Includes {
784 if pkg, hasPkg := packageFromLabel(hdr.Label); hasPkg {
785 absolute = append(absolute, pkg)
786 } else if pkg != "" {
787 relative = append(relative, pkg)
788 }
789 }
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400790 if len(relative)+len(existingRel) != 0 {
791 relative = android.FirstUniqueStrings(append(append([]string{}, existingRel...), relative...))
792 }
793 if len(absolute)+len(existingAbs) != 0 {
794 absolute = android.FirstUniqueStrings(append(append([]string{}, existingAbs...), absolute...))
795 }
Liz Kammer1263d9b2021-12-10 14:28:20 -0500796 return relative, absolute
797}
798
Cole Faust7071a052022-07-29 15:58:33 -0700799type YasmAttributes struct {
800 Srcs bazel.LabelListAttribute
801 Flags bazel.StringListAttribute
802 Include_dirs bazel.StringListAttribute
803}
804
805func bp2BuildYasm(ctx android.Bp2buildMutatorContext, m *Module, ca compilerAttributes) *bazel.LabelAttribute {
806 if ca.asmSrcs.IsEmpty() {
807 return nil
808 }
809
810 // Yasm needs the include directories from both local_includes and
811 // export_include_dirs. We don't care about actually exporting them from the
812 // yasm rule though, because they will also be present on the cc_ rule that
813 // wraps this yasm rule.
814 includes := ca.localIncludes.Clone()
815 bp2BuildPropParseHelper(ctx, m, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
816 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
817 if len(flagExporterProperties.Export_include_dirs) > 0 {
818 x := bazel.StringListAttribute{}
819 x.SetSelectValue(axis, config, flagExporterProperties.Export_include_dirs)
820 includes.Append(x)
821 }
822 }
823 })
824
825 ctx.CreateBazelTargetModule(
826 bazel.BazelTargetModuleProperties{
827 Rule_class: "yasm",
828 Bzl_load_location: "//build/bazel/rules/cc:yasm.bzl",
829 },
830 android.CommonAttributes{Name: m.Name() + "_yasm"},
831 &YasmAttributes{
832 Srcs: ca.asmSrcs,
833 Flags: ca.asFlags,
834 Include_dirs: *includes,
835 })
836
837 // We only want to add a dependency on the _yasm target if there are asm
838 // sources in the current configuration. If there are unconfigured asm
839 // sources, always add the dependency. Otherwise, add the dependency only
840 // on the configuration axes and values that had asm sources.
841 if len(ca.asmSrcs.Value.Includes) > 0 {
842 return bazel.MakeLabelAttribute(":" + m.Name() + "_yasm")
843 }
844
845 ret := &bazel.LabelAttribute{}
846 for _, axis := range ca.asmSrcs.SortedConfigurationAxes() {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800847 for cfg := range ca.asmSrcs.ConfigurableValues[axis] {
848 ret.SetSelectValue(axis, cfg, bazel.Label{Label: ":" + m.Name() + "_yasm"})
Cole Faust7071a052022-07-29 15:58:33 -0700849 }
850 }
851 return ret
852}
853
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000854// bp2BuildParseBaseProps returns all compiler, linker, library attributes of a cc module..
Liz Kammer12615db2021-09-28 09:19:17 -0400855func bp2BuildParseBaseProps(ctx android.Bp2buildMutatorContext, module *Module) baseAttributes {
Liz Kammere6583482021-10-19 13:56:10 -0400856 archVariantCompilerProps := module.GetArchVariantProperties(ctx, &BaseCompilerProperties{})
857 archVariantLinkerProps := module.GetArchVariantProperties(ctx, &BaseLinkerProperties{})
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000858 archVariantLibraryProperties := module.GetArchVariantProperties(ctx, &LibraryProperties{})
Liz Kammere6583482021-10-19 13:56:10 -0400859
Liz Kammere6583482021-10-19 13:56:10 -0400860 axisToConfigs := map[bazel.ConfigurationAxis]map[string]bool{}
861 allAxesAndConfigs := func(cp android.ConfigurationAxisToArchVariantProperties) {
862 for axis, configMap := range cp {
863 if _, ok := axisToConfigs[axis]; !ok {
864 axisToConfigs[axis] = map[string]bool{}
865 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800866 for cfg := range configMap {
867 axisToConfigs[axis][cfg] = true
Chris Parsonsa967f252021-09-23 16:34:35 -0400868 }
869 }
870 }
Liz Kammere6583482021-10-19 13:56:10 -0400871 allAxesAndConfigs(archVariantCompilerProps)
872 allAxesAndConfigs(archVariantLinkerProps)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000873 allAxesAndConfigs(archVariantLibraryProperties)
Chris Parsonsa967f252021-09-23 16:34:35 -0400874
Liz Kammere6583482021-10-19 13:56:10 -0400875 compilerAttrs := compilerAttributes{}
876 linkerAttrs := linkerAttributes{}
877
Vinh Tran367d89d2023-04-28 11:21:25 -0400878 var aidlLibs bazel.LabelList
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400879 var implementationHdrs, exportHdrs bazel.LabelListAttribute
Vinh Tran367d89d2023-04-28 11:21:25 -0400880
Chris Parsons7b3289b2023-01-26 17:30:44 -0500881 // Iterate through these axes in a deterministic order. This is required
882 // because processing certain dependencies may result in concatenating
883 // elements along other axes. (For example, processing NoConfig may result
884 // in elements being added to InApex). This is thus the only way to ensure
885 // that the order of entries in each list is in a predictable order.
886 for _, axis := range bazel.SortedConfigurationAxes(axisToConfigs) {
887 configs := axisToConfigs[axis]
Sasha Smundak39a301c2022-12-29 17:11:49 -0800888 for cfg := range configs {
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400889 var allHdrs []string
Sasha Smundak39a301c2022-12-29 17:11:49 -0800890 if baseCompilerProps, ok := archVariantCompilerProps[axis][cfg].(*BaseCompilerProperties); ok {
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400891 allHdrs = baseCompilerProps.Generated_headers
Spandan Das922171d2023-05-31 23:32:40 +0000892
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000893 if baseCompilerProps.Lex != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800894 compilerAttrs.lexopts.SetSelectValue(axis, cfg, baseCompilerProps.Lex.Flags)
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000895 }
Spandan Dasdf4c2132023-05-09 23:58:52 +0000896 if baseCompilerProps.Yacc != nil {
897 compilerAttrs.yaccFlags.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Flags)
898 compilerAttrs.yaccGenLocationHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_location_hh)
899 compilerAttrs.yaccGenPositionHeader.SetSelectValue(axis, cfg, baseCompilerProps.Yacc.Gen_position_hh)
900 }
Sasha Smundak39a301c2022-12-29 17:11:49 -0800901 (&compilerAttrs).bp2buildForAxisAndConfig(ctx, axis, cfg, baseCompilerProps)
Vinh Tran367d89d2023-04-28 11:21:25 -0400902 aidlLibs.Append(android.BazelLabelForModuleDeps(ctx, baseCompilerProps.Aidl.Libs))
Liz Kammere6583482021-10-19 13:56:10 -0400903 }
904
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400905 var exportedHdrs []string
Liz Kammere6583482021-10-19 13:56:10 -0400906
Sasha Smundak39a301c2022-12-29 17:11:49 -0800907 if baseLinkerProps, ok := archVariantLinkerProps[axis][cfg].(*BaseLinkerProperties); ok {
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400908 exportedHdrs = baseLinkerProps.Export_generated_headers
Liz Kammer48cdbeb2023-03-17 10:17:50 -0400909 (&linkerAttrs).bp2buildForAxisAndConfig(ctx, module, axis, cfg, baseLinkerProps)
Liz Kammere6583482021-10-19 13:56:10 -0400910 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400911
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400912 headers := maybePartitionExportedAndImplementationsDeps(ctx, !module.Binary(), allHdrs, exportedHdrs, android.BazelLabelForModuleDeps)
Liz Kammer084d6a92023-06-22 16:23:53 -0400913
Sasha Smundak39a301c2022-12-29 17:11:49 -0800914 implementationHdrs.SetSelectValue(axis, cfg, headers.implementation)
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400915 exportHdrs.SetSelectValue(axis, cfg, headers.export)
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000916
Sasha Smundak39a301c2022-12-29 17:11:49 -0800917 if libraryProps, ok := archVariantLibraryProperties[axis][cfg].(*LibraryProperties); ok {
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000918 if axis == bazel.NoConfigAxis {
Sam Delmerico75dbca22023-04-20 13:13:25 +0000919 if libraryProps.Stubs.Symbol_file != nil {
920 compilerAttrs.stubsSymbolFile = libraryProps.Stubs.Symbol_file
921 versions := android.CopyOf(libraryProps.Stubs.Versions)
922 normalizeVersions(ctx, versions)
923 versions = addCurrentVersionIfNotPresent(versions)
924 compilerAttrs.stubsVersions.SetSelectValue(axis, cfg, versions)
925 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000926 }
Spandan Das39ccf932023-05-26 18:03:39 +0000927 if stem := libraryProps.Stem; stem != nil {
928 compilerAttrs.stem.SetSelectValue(axis, cfg, stem)
929 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500930 if suffix := libraryProps.Suffix; suffix != nil {
Sasha Smundak39a301c2022-12-29 17:11:49 -0800931 compilerAttrs.suffix.SetSelectValue(axis, cfg, suffix)
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -0500932 }
Jingwen Chen0ee88a62022-01-07 14:55:29 +0000933 }
Liz Kammer084d6a92023-06-22 16:23:53 -0400934
Liz Kammere6583482021-10-19 13:56:10 -0400935 }
936 }
Vinh Tran9f6796a2022-08-16 13:10:31 -0400937
Liz Kammere6583482021-10-19 13:56:10 -0400938 compilerAttrs.convertStlProps(ctx, module)
939 (&linkerAttrs).convertStripProps(ctx, module)
940
Yu Liuf01a0f02022-12-07 15:45:30 -0800941 var nativeCoverage *bool
Yu Liu8d82ac52022-05-17 15:13:28 -0700942 if module.coverage != nil && module.coverage.Properties.Native_coverage != nil &&
943 !Bool(module.coverage.Properties.Native_coverage) {
Yu Liuf01a0f02022-12-07 15:45:30 -0800944 nativeCoverage = BoolPtr(false)
Yu Liu8d82ac52022-05-17 15:13:28 -0700945 }
946
Cole Faust912bc882023-03-08 12:29:50 -0800947 productVariableProps := android.ProductVariableProperties(ctx, ctx.Module())
Liz Kammere6583482021-10-19 13:56:10 -0400948
949 (&compilerAttrs).convertProductVariables(ctx, productVariableProps)
950 (&linkerAttrs).convertProductVariables(ctx, productVariableProps)
951
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400952 (&compilerAttrs).finalize(ctx, implementationHdrs, exportHdrs)
Liz Kammer54309532021-12-14 12:21:22 -0500953 (&linkerAttrs).finalize(ctx)
Liz Kammere6583482021-10-19 13:56:10 -0400954
Cole Faust7071a052022-07-29 15:58:33 -0700955 (&compilerAttrs.srcs).Add(bp2BuildYasm(ctx, module, compilerAttrs))
956
Liz Kammer0db0e342023-07-18 11:39:30 -0400957 (&linkerAttrs).deps.Append(compilerAttrs.exportGenruleHeaders)
958 (&linkerAttrs).implementationDeps.Append(compilerAttrs.genruleHeaders)
959
Liz Kammer5f5dbaa2023-07-17 17:44:08 -0400960 (&linkerAttrs).wholeArchiveDeps.Append(compilerAttrs.exportXsdSrcs)
961 (&linkerAttrs).implementationWholeArchiveDeps.Append(compilerAttrs.xsdSrcs)
962
Liz Kammer12615db2021-09-28 09:19:17 -0400963 protoDep := bp2buildProto(ctx, module, compilerAttrs.protoSrcs)
964
965 // bp2buildProto will only set wholeStaticLib or implementationWholeStaticLib, but we don't know
966 // which. This will add the newly generated proto library to the appropriate attribute and nothing
967 // to the other
968 (&linkerAttrs).wholeArchiveDeps.Add(protoDep.wholeStaticLib)
969 (&linkerAttrs).implementationWholeArchiveDeps.Add(protoDep.implementationWholeStaticLib)
Vinh Tranfde57eb2022-08-29 17:46:58 -0400970
Vinh Tran367d89d2023-04-28 11:21:25 -0400971 aidlDep := bp2buildCcAidlLibrary(
972 ctx, module,
973 compilerAttrs.aidlSrcs,
974 bazel.LabelListAttribute{
975 Value: aidlLibs,
976 },
977 linkerAttrs,
Vinh Trane6842942023-04-28 11:21:25 -0400978 compilerAttrs,
Vinh Tran367d89d2023-04-28 11:21:25 -0400979 )
Vinh Tranfde57eb2022-08-29 17:46:58 -0400980 if aidlDep != nil {
981 if lib, ok := module.linker.(*libraryDecorator); ok {
982 if proptools.Bool(lib.Properties.Aidl.Export_aidl_headers) {
983 (&linkerAttrs).wholeArchiveDeps.Add(aidlDep)
984 } else {
985 (&linkerAttrs).implementationWholeArchiveDeps.Add(aidlDep)
986 }
987 }
988 }
Liz Kammer12615db2021-09-28 09:19:17 -0400989
Spandan Dasdf4c2132023-05-09 23:58:52 +0000990 // Create a cc_yacc_static_library if srcs contains .y/.yy files
991 // This internal target will produce an .a file that will be statically linked to the parent library
992 if yaccDep := bp2buildCcYaccLibrary(ctx, compilerAttrs, linkerAttrs); yaccDep != nil {
993 (&linkerAttrs).implementationWholeArchiveDeps.Add(yaccDep)
994 }
995
Trevor Radcliffeef9c9002022-05-13 20:55:35 +0000996 convertedLSrcs := bp2BuildLex(ctx, module.Name(), compilerAttrs)
997 (&compilerAttrs).srcs.Add(&convertedLSrcs.srcName)
998 (&compilerAttrs).cSrcs.Add(&convertedLSrcs.cSrcName)
999
Vinh Tran99270ea2022-11-28 11:15:23 -05001000 if module.afdo != nil && module.afdo.Properties.Afdo {
1001 fdoProfileDep := bp2buildFdoProfile(ctx, module)
1002 if fdoProfileDep != nil {
1003 (&compilerAttrs).fdoProfile.SetValue(*fdoProfileDep)
1004 }
1005 }
1006
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001007 if !compilerAttrs.syspropSrcs.IsEmpty() {
1008 (&linkerAttrs).wholeArchiveDeps.Add(bp2buildCcSysprop(ctx, module.Name(), module.Properties.Min_sdk_version, compilerAttrs.syspropSrcs))
1009 }
1010
Zi Wang9f609db2023-01-04 11:06:54 -08001011 linkerAttrs.wholeArchiveDeps.Prepend = true
1012 linkerAttrs.deps.Prepend = true
1013 compilerAttrs.localIncludes.Prepend = true
1014 compilerAttrs.absoluteIncludes.Prepend = true
1015 compilerAttrs.hdrs.Prepend = true
1016
Alixe2667872023-04-24 14:57:32 +00001017 convertedRsSrcs, rsAbsIncludes, rsLocalIncludes := bp2buildRScript(ctx, module, compilerAttrs)
1018 (&compilerAttrs).srcs.Add(&convertedRsSrcs)
1019 (&compilerAttrs).absoluteIncludes.Append(rsAbsIncludes)
1020 (&compilerAttrs).localIncludes.Append(rsLocalIncludes)
1021 (&compilerAttrs).localIncludes.Value = android.FirstUniqueStrings(compilerAttrs.localIncludes.Value)
1022
Trevor Radcliffed9b7f172023-08-09 22:21:38 +00001023 sanitizerValues := bp2buildSanitizerFeatures(ctx, module)
1024
1025 features := compilerAttrs.features.Clone().Append(linkerAttrs.features).Append(sanitizerValues.features)
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +00001026 features = features.Append(bp2buildLtoFeatures(ctx, module))
Trevor Radcliffea8b44162023-04-14 18:25:24 +00001027 features = features.Append(convertHiddenVisibilityToFeatureBase(ctx, module))
Cole Faust5fa4e962022-08-22 14:31:04 -07001028 features.DeduplicateAxesFromBase()
1029
Trevor Radcliffed9b7f172023-08-09 22:21:38 +00001030 compilerAttrs.copts = *compilerAttrs.copts.Append(sanitizerValues.copts)
1031 compilerAttrs.additionalCompilerInputs = *compilerAttrs.additionalCompilerInputs.Append(sanitizerValues.additionalCompilerInputs)
1032
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +00001033 addMuslSystemDynamicDeps(ctx, linkerAttrs)
1034
Liz Kammere6583482021-10-19 13:56:10 -04001035 return baseAttributes{
1036 compilerAttrs,
1037 linkerAttrs,
Cole Faust5fa4e962022-08-22 14:31:04 -07001038 *features,
Liz Kammer12615db2021-09-28 09:19:17 -04001039 protoDep.protoDep,
Vinh Tran9f6796a2022-08-16 13:10:31 -04001040 aidlDep,
Yu Liuf01a0f02022-12-07 15:45:30 -08001041 nativeCoverage,
Jingwen Chen107c0de2021-04-09 10:43:12 +00001042 }
1043}
1044
Spandan Dasdf4c2132023-05-09 23:58:52 +00001045type ccYaccLibraryAttributes struct {
1046 Src bazel.LabelAttribute
1047 Flags bazel.StringListAttribute
1048 Gen_location_hh bazel.BoolAttribute
1049 Gen_position_hh bazel.BoolAttribute
1050 Local_includes bazel.StringListAttribute
1051 Implementation_deps bazel.LabelListAttribute
1052 Implementation_dynamic_deps bazel.LabelListAttribute
1053}
1054
1055func bp2buildCcYaccLibrary(ctx android.Bp2buildMutatorContext, ca compilerAttributes, la linkerAttributes) *bazel.LabelAttribute {
1056 if ca.yaccSrc == nil {
1057 return nil
1058 }
1059 yaccLibraryLabel := ctx.Module().Name() + "_yacc"
1060 ctx.CreateBazelTargetModule(
1061 bazel.BazelTargetModuleProperties{
1062 Rule_class: "cc_yacc_static_library",
1063 Bzl_load_location: "//build/bazel/rules/cc:cc_yacc_library.bzl",
1064 },
1065 android.CommonAttributes{
1066 Name: yaccLibraryLabel,
1067 },
1068 &ccYaccLibraryAttributes{
1069 Src: *ca.yaccSrc,
1070 Flags: ca.yaccFlags,
1071 Gen_location_hh: ca.yaccGenLocationHeader,
1072 Gen_position_hh: ca.yaccGenPositionHeader,
1073 Local_includes: ca.localIncludes,
1074 Implementation_deps: la.implementationDeps,
1075 Implementation_dynamic_deps: la.implementationDynamicDeps,
1076 },
1077 )
1078
1079 yaccLibrary := &bazel.LabelAttribute{
1080 Value: &bazel.Label{
1081 Label: ":" + yaccLibraryLabel,
1082 },
1083 }
1084 return yaccLibrary
1085}
1086
Trevor Radcliffe0d1b4022022-12-12 22:26:34 +00001087// As a workaround for b/261657184, we are manually adding the default value
1088// of system_dynamic_deps for the linux_musl os.
1089// TODO: Solve this properly
1090func addMuslSystemDynamicDeps(ctx android.Bp2buildMutatorContext, attrs linkerAttributes) {
1091 systemDynamicDeps := attrs.systemDynamicDeps.SelectValue(bazel.OsConfigurationAxis, "linux_musl")
1092 if attrs.systemDynamicDeps.HasAxisSpecificValues(bazel.OsConfigurationAxis) && systemDynamicDeps.IsNil() {
1093 attrs.systemDynamicDeps.SetSelectValue(bazel.OsConfigurationAxis, "linux_musl", android.BazelLabelForModuleDeps(ctx, config.MuslDefaultSharedLibraries))
1094 }
1095}
1096
Vinh Tran99270ea2022-11-28 11:15:23 -05001097type fdoProfileAttributes struct {
1098 Absolute_path_profile string
1099}
1100
1101func bp2buildFdoProfile(
1102 ctx android.Bp2buildMutatorContext,
1103 m *Module,
1104) *bazel.Label {
1105 for _, project := range globalAfdoProfileProjects {
Vinh Tranbc9c8b42022-12-09 12:03:52 -05001106 // Ensure handcrafted BUILD file exists in the project
1107 BUILDPath := android.ExistentPathForSource(ctx, project, "BUILD")
1108 if BUILDPath.Valid() {
1109 // We handcraft a BUILD file with fdo_profile targets that use the existing profiles in the project
1110 // This implementation is assuming that every afdo profile in globalAfdoProfileProjects already has
1111 // an associated fdo_profile target declared in the same package.
1112 // TODO(b/260714900): Handle arch-specific afdo profiles (e.g. `<module-name>-arm<64>.afdo`)
1113 path := android.ExistentPathForSource(ctx, project, m.Name()+".afdo")
1114 if path.Valid() {
1115 // FIXME: Some profiles only exist internally and are not released to AOSP.
1116 // When generated BUILD files are checked in, we'll run into merge conflict.
1117 // The cc_library_shared target in AOSP won't have reference to an fdo_profile target because
1118 // the profile doesn't exist. Internally, the same cc_library_shared target will
1119 // have reference to the fdo_profile.
1120 // For more context, see b/258682955#comment2
1121 fdoProfileLabel := "//" + strings.TrimSuffix(project, "/") + ":" + m.Name()
1122 return &bazel.Label{
1123 Label: fdoProfileLabel,
1124 }
Vinh Tran99270ea2022-11-28 11:15:23 -05001125 }
1126 }
1127 }
1128
1129 return nil
1130}
1131
Vinh Tran9f6796a2022-08-16 13:10:31 -04001132func bp2buildCcAidlLibrary(
1133 ctx android.Bp2buildMutatorContext,
1134 m *Module,
Vinh Tran367d89d2023-04-28 11:21:25 -04001135 aidlSrcs bazel.LabelListAttribute,
1136 aidlLibs bazel.LabelListAttribute,
Vinh Tran395a1e92022-09-16 18:27:29 -04001137 linkerAttrs linkerAttributes,
Vinh Trane6842942023-04-28 11:21:25 -04001138 compilerAttrs compilerAttributes,
Vinh Tran9f6796a2022-08-16 13:10:31 -04001139) *bazel.LabelAttribute {
Vinh Tran367d89d2023-04-28 11:21:25 -04001140 var aidlLibsFromSrcs, aidlFiles bazel.LabelListAttribute
1141 apexAvailableTags := android.ApexAvailableTagsWithoutTestApexes(ctx.(android.TopDownMutatorContext), ctx.Module())
1142
1143 if !aidlSrcs.IsEmpty() {
1144 aidlLibsFromSrcs, aidlFiles = aidlSrcs.Partition(func(src bazel.Label) bool {
Vinh Trana3b8b782022-09-14 11:40:24 -04001145 if fg, ok := android.ToFileGroupAsLibrary(ctx, src.OriginalModuleName); ok &&
1146 fg.ShouldConvertToAidlLibrary(ctx) {
1147 return true
1148 }
1149 return false
1150 })
Vinh Tran9f6796a2022-08-16 13:10:31 -04001151
Vinh Tran367d89d2023-04-28 11:21:25 -04001152 if !aidlFiles.IsEmpty() {
Vinh Trana3b8b782022-09-14 11:40:24 -04001153 aidlLibName := m.Name() + "_aidl_library"
1154 ctx.CreateBazelTargetModule(
1155 bazel.BazelTargetModuleProperties{
1156 Rule_class: "aidl_library",
Sam Delmericoe55bf082023-03-31 09:47:28 -04001157 Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
Vinh Trana3b8b782022-09-14 11:40:24 -04001158 },
Vinh Tran367d89d2023-04-28 11:21:25 -04001159 android.CommonAttributes{
1160 Name: aidlLibName,
Liz Kammer2b3f56e2023-03-23 11:51:49 -04001161 Tags: apexAvailableTags,
Vinh Trana3b8b782022-09-14 11:40:24 -04001162 },
Vinh Tran367d89d2023-04-28 11:21:25 -04001163 &aidlLibraryAttributes{
1164 Srcs: aidlFiles,
Vinh Trana3b8b782022-09-14 11:40:24 -04001165 },
1166 )
Vinh Tran367d89d2023-04-28 11:21:25 -04001167 aidlLibsFromSrcs.Add(&bazel.LabelAttribute{Value: &bazel.Label{Label: ":" + aidlLibName}})
Vinh Trana3b8b782022-09-14 11:40:24 -04001168 }
Vinh Tran9f6796a2022-08-16 13:10:31 -04001169 }
1170
Vinh Tran367d89d2023-04-28 11:21:25 -04001171 allAidlLibs := aidlLibs.Clone()
1172 allAidlLibs.Append(aidlLibsFromSrcs)
1173
1174 if !allAidlLibs.IsEmpty() {
1175 ccAidlLibrarylabel := m.Name() + "_cc_aidl_library"
1176 // Since parent cc_library already has these dependencies, we can add them as implementation
1177 // deps so that they don't re-export
1178 implementationDeps := linkerAttrs.deps.Clone()
1179 implementationDeps.Append(linkerAttrs.implementationDeps)
1180 implementationDynamicDeps := linkerAttrs.dynamicDeps.Clone()
1181 implementationDynamicDeps.Append(linkerAttrs.implementationDynamicDeps)
1182
1183 sdkAttrs := bp2BuildParseSdkAttributes(m)
1184
Vinh Trane6842942023-04-28 11:21:25 -04001185 exportedIncludes := bp2BuildParseExportedIncludes(ctx, m, &compilerAttrs.includes)
1186 includeAttrs := includesAttributes{
1187 Export_includes: exportedIncludes.Includes,
1188 Export_absolute_includes: exportedIncludes.AbsoluteIncludes,
1189 Export_system_includes: exportedIncludes.SystemIncludes,
1190 Local_includes: compilerAttrs.localIncludes,
1191 Absolute_includes: compilerAttrs.absoluteIncludes,
1192 }
1193
Vinh Tran367d89d2023-04-28 11:21:25 -04001194 ctx.CreateBazelTargetModule(
1195 bazel.BazelTargetModuleProperties{
1196 Rule_class: "cc_aidl_library",
1197 Bzl_load_location: "//build/bazel/rules/cc:cc_aidl_library.bzl",
1198 },
1199 android.CommonAttributes{Name: ccAidlLibrarylabel},
1200 &ccAidlLibraryAttributes{
1201 Deps: *allAidlLibs,
1202 Implementation_deps: *implementationDeps,
1203 Implementation_dynamic_deps: *implementationDynamicDeps,
1204 Tags: apexAvailableTags,
1205 sdkAttributes: sdkAttrs,
Vinh Trane6842942023-04-28 11:21:25 -04001206 includesAttributes: includeAttrs,
Vinh Tran367d89d2023-04-28 11:21:25 -04001207 },
1208 )
1209 label := &bazel.LabelAttribute{
1210 Value: &bazel.Label{
1211 Label: ":" + ccAidlLibrarylabel,
1212 },
1213 }
1214 return label
1215 }
1216
Vinh Trana3b8b782022-09-14 11:40:24 -04001217 return nil
Vinh Tran9f6796a2022-08-16 13:10:31 -04001218}
1219
Yu Liufc603162022-03-01 15:44:08 -08001220func bp2BuildParseSdkAttributes(module *Module) sdkAttributes {
Trevor Radcliffe58ea4512022-04-07 20:36:39 +00001221 return sdkAttributes{
1222 Sdk_version: module.Properties.Sdk_version,
Yu Liufc603162022-03-01 15:44:08 -08001223 Min_sdk_version: module.Properties.Min_sdk_version,
1224 }
1225}
1226
1227type sdkAttributes struct {
1228 Sdk_version *string
1229 Min_sdk_version *string
1230}
1231
Jingwen Chen107c0de2021-04-09 10:43:12 +00001232// Convenience struct to hold all attributes parsed from linker properties.
1233type linkerAttributes struct {
Liz Kammer54309532021-12-14 12:21:22 -05001234 deps bazel.LabelListAttribute
1235 implementationDeps bazel.LabelListAttribute
1236 dynamicDeps bazel.LabelListAttribute
1237 implementationDynamicDeps bazel.LabelListAttribute
Cole Faust6b29f592022-08-09 09:50:56 -07001238 runtimeDeps bazel.LabelListAttribute
Liz Kammer54309532021-12-14 12:21:22 -05001239 wholeArchiveDeps bazel.LabelListAttribute
1240 implementationWholeArchiveDeps bazel.LabelListAttribute
1241 systemDynamicDeps bazel.LabelListAttribute
Liz Kammerb4928432023-06-02 18:43:36 -04001242 usedSystemDynamicDepAsStaticDep map[string]bool
Liz Kammer54309532021-12-14 12:21:22 -05001243 usedSystemDynamicDepAsDynamicDep map[string]bool
Liz Kammer7a210ac2021-09-22 15:52:58 -04001244
Rupert Shuttleworth484aa252021-12-10 07:22:53 -05001245 useVersionLib bazel.BoolAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001246 linkopts bazel.StringListAttribute
Liz Kammerd2871182021-10-04 13:54:37 -04001247 additionalLinkerInputs bazel.LabelListAttribute
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001248 stripKeepSymbols bazel.BoolAttribute
1249 stripKeepSymbolsAndDebugFrame bazel.BoolAttribute
1250 stripKeepSymbolsList bazel.StringListAttribute
1251 stripAll bazel.BoolAttribute
1252 stripNone bazel.BoolAttribute
Liz Kammer0eae52e2021-10-06 10:32:26 -04001253 features bazel.StringListAttribute
Rupert Shuttleworth143be942021-05-09 23:55:51 -04001254}
1255
Liz Kammer54309532021-12-14 12:21:22 -05001256var (
1257 soongSystemSharedLibs = []string{"libc", "libm", "libdl"}
Liz Kammerbaced712022-09-16 09:01:29 -04001258 versionLib = "libbuildversion"
Liz Kammer54309532021-12-14 12:21:22 -05001259)
1260
Vinh Tran85fb07c2022-09-16 16:17:48 -04001261// resolveTargetApex re-adds the shared and static libs in target.apex.exclude_shared|static_libs props to non-apex variant
1262// since all libs are already excluded by default
Liz Kammer748d7072023-01-25 12:07:43 -05001263func (la *linkerAttributes) resolveTargetApexProp(ctx android.BazelConversionPathContext, props *BaseLinkerProperties) {
1264 excludeSharedLibs := bazelLabelForSharedDeps(ctx, props.Target.Apex.Exclude_shared_libs)
1265 sharedExcludes := bazel.LabelList{Excludes: excludeSharedLibs.Includes}
1266 sharedExcludesLabelList := bazel.LabelListAttribute{}
1267 sharedExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, sharedExcludes)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001268
Liz Kammer748d7072023-01-25 12:07:43 -05001269 la.dynamicDeps.Append(sharedExcludesLabelList)
1270 la.implementationDynamicDeps.Append(sharedExcludesLabelList)
1271
1272 excludeStaticLibs := bazelLabelForStaticDeps(ctx, props.Target.Apex.Exclude_static_libs)
1273 staticExcludes := bazel.LabelList{Excludes: excludeStaticLibs.Includes}
1274 staticExcludesLabelList := bazel.LabelListAttribute{}
1275 staticExcludesLabelList.SetSelectValue(bazel.InApexAxis, bazel.InApex, staticExcludes)
1276
1277 la.deps.Append(staticExcludesLabelList)
1278 la.implementationDeps.Append(staticExcludesLabelList)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001279}
1280
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001281func (la *linkerAttributes) bp2buildForAxisAndConfig(ctx android.BazelConversionPathContext, module *Module, axis bazel.ConfigurationAxis, config string, props *BaseLinkerProperties) {
1282 isBinary := module.Binary()
Liz Kammere6583482021-10-19 13:56:10 -04001283 // Use a single variable to capture usage of nocrt in arch variants, so there's only 1 error message for this module
1284 var axisFeatures []string
Liz Kammer7a210ac2021-09-22 15:52:58 -04001285
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001286 wholeStaticLibs := android.FirstUniqueStrings(props.Whole_static_libs)
Liz Kammerbaced712022-09-16 09:01:29 -04001287 staticLibs := android.FirstUniqueStrings(android.RemoveListFromList(props.Static_libs, wholeStaticLibs))
1288 if axis == bazel.NoConfigAxis {
1289 la.useVersionLib.SetSelectValue(axis, config, props.Use_version_lib)
1290 if proptools.Bool(props.Use_version_lib) {
1291 versionLibAlreadyInDeps := android.InList(versionLib, wholeStaticLibs)
1292 // remove from static libs so there is no duplicate dependency
1293 _, staticLibs = android.RemoveFromList(versionLib, staticLibs)
1294 // only add the dep if it is not in progress
1295 if !versionLibAlreadyInDeps {
Yu Liufe978fd2023-04-24 16:37:18 -07001296 wholeStaticLibs = append(wholeStaticLibs, versionLib)
Liz Kammerbaced712022-09-16 09:01:29 -04001297 }
1298 }
1299 }
1300
Liz Kammere6583482021-10-19 13:56:10 -04001301 // Excludes to parallel Soong:
1302 // 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 -04001303 la.wholeArchiveDeps.SetSelectValue(axis, config, bazelLabelForWholeDepsExcludes(ctx, wholeStaticLibs, props.Exclude_static_libs))
Liz Kammercc2c1ef2022-03-21 09:03:29 -04001304
Liz Kammerb4928432023-06-02 18:43:36 -04001305 if isBinary && module.StaticExecutable() {
1306 usedSystemStatic := android.FilterListPred(staticLibs, func(s string) bool {
1307 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, props.Exclude_static_libs)
1308 })
1309
1310 for _, el := range usedSystemStatic {
1311 if la.usedSystemDynamicDepAsStaticDep == nil {
1312 la.usedSystemDynamicDepAsStaticDep = map[string]bool{}
1313 }
1314 la.usedSystemDynamicDepAsStaticDep[el] = true
1315 }
1316 }
Vinh Tran85fb07c2022-09-16 16:17:48 -04001317 staticDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1318 ctx,
1319 !isBinary,
1320 staticLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001321 props.Exclude_static_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001322 props.Export_static_lib_headers,
1323 bazelLabelForStaticDepsExcludes,
1324 )
Liz Kammer7a210ac2021-09-22 15:52:58 -04001325
Liz Kammere6583482021-10-19 13:56:10 -04001326 headerLibs := android.FirstUniqueStrings(props.Header_libs)
1327 hDeps := maybePartitionExportedAndImplementationsDeps(ctx, !isBinary, headerLibs, props.Export_header_lib_headers, bazelLabelForHeaderDeps)
Jingwen Chen63930982021-03-24 10:04:33 -04001328
Liz Kammere6583482021-10-19 13:56:10 -04001329 (&hDeps.export).Append(staticDeps.export)
1330 la.deps.SetSelectValue(axis, config, hDeps.export)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001331
Liz Kammere6583482021-10-19 13:56:10 -04001332 (&hDeps.implementation).Append(staticDeps.implementation)
1333 la.implementationDeps.SetSelectValue(axis, config, hDeps.implementation)
Liz Kammer0eae52e2021-10-06 10:32:26 -04001334
Liz Kammere6583482021-10-19 13:56:10 -04001335 systemSharedLibs := props.System_shared_libs
1336 // systemSharedLibs distinguishes between nil/empty list behavior:
1337 // nil -> use default values
1338 // empty list -> no values specified
1339 if len(systemSharedLibs) > 0 {
1340 systemSharedLibs = android.FirstUniqueStrings(systemSharedLibs)
1341 }
1342 la.systemDynamicDeps.SetSelectValue(axis, config, bazelLabelForSharedDeps(ctx, systemSharedLibs))
1343
1344 sharedLibs := android.FirstUniqueStrings(props.Shared_libs)
Liz Kammer54309532021-12-14 12:21:22 -05001345 excludeSharedLibs := props.Exclude_shared_libs
1346 usedSystem := android.FilterListPred(sharedLibs, func(s string) bool {
1347 return android.InList(s, soongSystemSharedLibs) && !android.InList(s, excludeSharedLibs)
1348 })
Liz Kammerb4928432023-06-02 18:43:36 -04001349
Liz Kammer54309532021-12-14 12:21:22 -05001350 for _, el := range usedSystem {
1351 if la.usedSystemDynamicDepAsDynamicDep == nil {
1352 la.usedSystemDynamicDepAsDynamicDep = map[string]bool{}
1353 }
1354 la.usedSystemDynamicDepAsDynamicDep[el] = true
1355 }
1356
Vinh Tran85fb07c2022-09-16 16:17:48 -04001357 sharedDeps := maybePartitionExportedAndImplementationsDepsExcludes(
1358 ctx,
1359 !isBinary,
1360 sharedLibs,
Liz Kammer748d7072023-01-25 12:07:43 -05001361 props.Exclude_shared_libs,
Vinh Tran85fb07c2022-09-16 16:17:48 -04001362 props.Export_shared_lib_headers,
1363 bazelLabelForSharedDepsExcludes,
1364 )
Liz Kammere6583482021-10-19 13:56:10 -04001365 la.dynamicDeps.SetSelectValue(axis, config, sharedDeps.export)
1366 la.implementationDynamicDeps.SetSelectValue(axis, config, sharedDeps.implementation)
Liz Kammer748d7072023-01-25 12:07:43 -05001367 la.resolveTargetApexProp(ctx, props)
Vinh Tran85fb07c2022-09-16 16:17:48 -04001368
Wei Li81852ca2022-07-27 00:22:06 -07001369 if axis == bazel.NoConfigAxis || (axis == bazel.OsConfigurationAxis && config == bazel.OsAndroid) {
Yu Liu10174ff2023-02-21 12:05:26 -08001370 // If a dependency in la.implementationDynamicDeps or la.dynamicDeps has stubs, its
1371 // stub variant should be used when the dependency is linked in a APEX. The
1372 // dependencies in NoConfigAxis and OsConfigurationAxis/OsAndroid are grouped by
1373 // having stubs or not, so Bazel select() statement can be used to choose
1374 // source/stub variants of them.
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001375 apexAvailable := module.ApexAvailable()
Spandan Dasac693b22023-04-24 00:07:38 +00001376 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.export, &la.dynamicDeps, 0, false)
1377 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, sharedDeps.implementation, &la.implementationDynamicDeps, 1, false)
1378 if len(systemSharedLibs) > 0 {
1379 setStubsForDynamicDeps(ctx, axis, config, apexAvailable, bazelLabelForSharedDeps(ctx, systemSharedLibs), &la.systemDynamicDeps, 2, true)
1380 }
Wei Li81852ca2022-07-27 00:22:06 -07001381 }
Liz Kammere6583482021-10-19 13:56:10 -04001382
1383 if !BoolDefault(props.Pack_relocations, packRelocationsDefault) {
1384 axisFeatures = append(axisFeatures, "disable_pack_relocations")
1385 }
1386
1387 if Bool(props.Allow_undefined_symbols) {
1388 axisFeatures = append(axisFeatures, "-no_undefined_symbols")
1389 }
1390
1391 var linkerFlags []string
1392 if len(props.Ldflags) > 0 {
Liz Kammerf38a8372022-02-04 15:39:00 -05001393 linkerFlags = append(linkerFlags, proptools.NinjaEscapeList(props.Ldflags)...)
Liz Kammere6583482021-10-19 13:56:10 -04001394 // binaries remove static flag if -shared is in the linker flags
1395 if isBinary && android.InList("-shared", linkerFlags) {
1396 axisFeatures = append(axisFeatures, "-static_flag")
1397 }
1398 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001399
Alex Márquez Pérez Muñíz Díaz Puras Thaureaux01ec55e2023-01-30 22:53:04 +00001400 if !props.libCrt() {
1401 axisFeatures = append(axisFeatures, "-use_libcrt")
1402 }
1403 if !props.crt() {
1404 axisFeatures = append(axisFeatures, "-link_crt")
1405 }
1406
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001407 // This must happen before the addition of flags for Version Script and
1408 // Dynamic List, as these flags must be split on spaces and those must not
1409 linkerFlags = parseCommandLineFlags(linkerFlags, filterOutClangUnknownCflags)
1410
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001411 additionalLinkerInputs := bazel.LabelList{}
Liz Kammere6583482021-10-19 13:56:10 -04001412 if props.Version_script != nil {
1413 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Version_script)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001414 additionalLinkerInputs.Add(&label)
Liz Kammere6583482021-10-19 13:56:10 -04001415 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--version-script,$(location %s)", label.Label))
Trevor Radcliffef06dd912023-05-19 14:51:41 +00001416 axisFeatures = append(axisFeatures, "android_cfi_exports_map")
Liz Kammere6583482021-10-19 13:56:10 -04001417 }
Alix773adaa2022-04-27 17:49:34 +00001418
1419 if props.Dynamic_list != nil {
1420 label := android.BazelLabelForModuleSrcSingle(ctx, *props.Dynamic_list)
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001421 additionalLinkerInputs.Add(&label)
Alix773adaa2022-04-27 17:49:34 +00001422 linkerFlags = append(linkerFlags, fmt.Sprintf("-Wl,--dynamic-list,$(location %s)", label.Label))
1423 }
1424
Trevor Radcliffe37ec2f72022-09-27 01:46:01 +00001425 la.additionalLinkerInputs.SetSelectValue(axis, config, additionalLinkerInputs)
Spandan Dasfb04c412023-05-15 18:35:36 +00001426 if axis == bazel.OsConfigurationAxis && (config == bazel.OsDarwin || config == bazel.OsLinux || config == bazel.OsWindows) {
1427 linkerFlags = append(linkerFlags, props.Host_ldlibs...)
1428 }
Trevor Radcliffeea6a45d2022-09-20 18:58:01 +00001429 la.linkopts.SetSelectValue(axis, config, linkerFlags)
Liz Kammere6583482021-10-19 13:56:10 -04001430
1431 if axisFeatures != nil {
1432 la.features.SetSelectValue(axis, config, axisFeatures)
1433 }
Cole Faust6b29f592022-08-09 09:50:56 -07001434
1435 runtimeDeps := android.BazelLabelForModuleDepsExcludes(ctx, props.Runtime_libs, props.Exclude_runtime_libs)
1436 if !runtimeDeps.IsEmpty() {
1437 la.runtimeDeps.SetSelectValue(axis, config, runtimeDeps)
1438 }
Liz Kammere6583482021-10-19 13:56:10 -04001439}
1440
Spandan Das2518c022023-03-17 03:02:32 +00001441var (
1442 apiSurfaceModuleLibCurrentPackage = "@api_surfaces//" + android.ModuleLibApi.String() + "/current:"
1443)
1444
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001445func availableToSameApexes(a, b []string) bool {
1446 if len(a) == 0 && len(b) == 0 {
1447 return true
1448 }
1449 differ, _, _ := android.ListSetDifference(a, b)
1450 return !differ
1451}
1452
Spandan Das4242f102023-04-19 22:31:54 +00001453var (
Spandan Das9cad90f2023-05-04 17:15:44 +00001454 apiDomainConfigSettingKey = android.NewOnceKey("apiDomainConfigSettingKey")
1455 apiDomainConfigSettingLock sync.Mutex
Spandan Das4242f102023-04-19 22:31:54 +00001456)
1457
Spandan Das9cad90f2023-05-04 17:15:44 +00001458func getApiDomainConfigSettingMap(config android.Config) *map[string]bool {
1459 return config.Once(apiDomainConfigSettingKey, func() interface{} {
Spandan Das4242f102023-04-19 22:31:54 +00001460 return &map[string]bool{}
1461 }).(*map[string]bool)
1462}
1463
Spandan Das9cad90f2023-05-04 17:15:44 +00001464var (
1465 testApexNameToApiDomain = map[string]string{
1466 "test_broken_com.android.art": "com.android.art",
1467 }
1468)
1469
Spandan Dasa43ae132023-05-08 18:33:16 +00001470// GetApiDomain returns the canonical name of the apex. This is synonymous to the apex_name definition.
1471// https://cs.android.com/android/_/android/platform/build/soong/+/e3f0281b8897da1fe23b2f4f3a05f1dc87bcc902:apex/prebuilt.go;l=81-83;drc=2dc7244af985a6ad701b22f1271e606cabba527f;bpv=1;bpt=0
1472// For test apexes, it uses a naming convention heuristic to determine the api domain.
1473// TODO (b/281548611): Move this build/soong/android
1474func GetApiDomain(apexName string) string {
Spandan Das9cad90f2023-05-04 17:15:44 +00001475 if apiDomain, exists := testApexNameToApiDomain[apexName]; exists {
1476 return apiDomain
1477 }
1478 // Remove `test_` prefix
1479 return strings.TrimPrefix(apexName, "test_")
1480}
1481
Spandan Das4242f102023-04-19 22:31:54 +00001482// Create a config setting for this apex in build/bazel/rules/apex
1483// The use case for this is stub/impl selection in cc libraries
1484// Long term, these config_setting(s) should be colocated with the respective apex definitions.
1485// Note that this is an anti-pattern: The config_setting should be created from the apex definition
1486// and not from a cc_library.
1487// This anti-pattern is needed today since not all apexes have been allowlisted.
1488func createInApexConfigSetting(ctx android.TopDownMutatorContext, apexName string) {
1489 if apexName == android.AvailableToPlatform || apexName == android.AvailableToAnyApex {
1490 // These correspond to android-non_apex and android-in_apex
1491 return
1492 }
Spandan Das9cad90f2023-05-04 17:15:44 +00001493 apiDomainConfigSettingLock.Lock()
1494 defer apiDomainConfigSettingLock.Unlock()
Spandan Das4242f102023-04-19 22:31:54 +00001495
1496 // Return if a config_setting has already been created
Spandan Dasa43ae132023-05-08 18:33:16 +00001497 apiDomain := GetApiDomain(apexName)
Spandan Das9cad90f2023-05-04 17:15:44 +00001498 acsm := getApiDomainConfigSettingMap(ctx.Config())
1499 if _, exists := (*acsm)[apiDomain]; exists {
Spandan Das4242f102023-04-19 22:31:54 +00001500 return
1501 }
Spandan Das9cad90f2023-05-04 17:15:44 +00001502 (*acsm)[apiDomain] = true
Spandan Das4242f102023-04-19 22:31:54 +00001503
1504 csa := bazel.ConfigSettingAttributes{
1505 Flag_values: bazel.StringMapAttribute{
Spandan Das9cad90f2023-05-04 17:15:44 +00001506 "//build/bazel/rules/apex:api_domain": apiDomain,
Spandan Das4242f102023-04-19 22:31:54 +00001507 },
Spandan Das9cad90f2023-05-04 17:15:44 +00001508 // Constraint this to android
1509 Constraint_values: bazel.MakeLabelListAttribute(
1510 bazel.MakeLabelList(
1511 []bazel.Label{
1512 bazel.Label{Label: "//build/bazel/platforms/os:android"},
1513 },
1514 ),
1515 ),
Spandan Das4242f102023-04-19 22:31:54 +00001516 }
1517 ca := android.CommonAttributes{
Spandan Das9cad90f2023-05-04 17:15:44 +00001518 Name: apiDomain,
Spandan Das4242f102023-04-19 22:31:54 +00001519 }
1520 ctx.CreateBazelConfigSetting(
1521 csa,
1522 ca,
1523 "build/bazel/rules/apex",
1524 )
1525}
1526
1527func inApexConfigSetting(apexAvailable string) string {
1528 if apexAvailable == android.AvailableToPlatform {
Spandan Das6d4d9da2023-04-18 06:20:40 +00001529 return bazel.AndroidPlatform
Spandan Das4242f102023-04-19 22:31:54 +00001530 }
1531 if apexAvailable == android.AvailableToAnyApex {
1532 return bazel.AndroidAndInApex
1533 }
Spandan Dasa43ae132023-05-08 18:33:16 +00001534 apiDomain := GetApiDomain(apexAvailable)
Spandan Das9cad90f2023-05-04 17:15:44 +00001535 return "//build/bazel/rules/apex:" + apiDomain
Spandan Das4242f102023-04-19 22:31:54 +00001536}
1537
Spandan Das6d4d9da2023-04-18 06:20:40 +00001538// Inputs to stub vs impl selection.
1539type stubSelectionInfo struct {
1540 // Label of the implementation library (e.g. //bionic/libc:libc)
1541 impl bazel.Label
1542 // Axis containing the implementation library
1543 axis bazel.ConfigurationAxis
1544 // Axis key containing the implementation library
1545 config string
1546 // API domain of the apex
1547 // For test apexes (test_com.android.foo), this will be the source apex (com.android.foo)
1548 apiDomain string
1549 // List of dep labels
1550 dynamicDeps *bazel.LabelListAttribute
1551 // Boolean value for determining if the dep is in the same api domain
1552 // If false, the label will be rewritten to to the stub label
1553 sameApiDomain bool
1554}
1555
1556func useStubOrImplInApexWithName(ssi stubSelectionInfo) {
1557 lib := ssi.impl
1558 if !ssi.sameApiDomain {
1559 lib = bazel.Label{
1560 Label: apiSurfaceModuleLibCurrentPackage + strings.TrimPrefix(lib.OriginalModuleName, ":"),
1561 }
1562 }
1563 // Create a select statement specific to this apex
1564 inApexSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain))
1565 (&inApexSelectValue).Append(bazel.MakeLabelList([]bazel.Label{lib}))
1566 ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, inApexConfigSetting(ssi.apiDomain), bazel.FirstUniqueBazelLabelList(inApexSelectValue))
1567 // Delete the library from the common config for this apex
1568 implDynamicDeps := ssi.dynamicDeps.SelectValue(ssi.axis, ssi.config)
1569 implDynamicDeps = bazel.SubtractBazelLabelList(implDynamicDeps, bazel.MakeLabelList([]bazel.Label{ssi.impl}))
1570 ssi.dynamicDeps.SetSelectValue(ssi.axis, ssi.config, implDynamicDeps)
1571 if ssi.axis == bazel.NoConfigAxis {
1572 // Set defaults. Defaults (i.e. host) should use impl and not stubs.
1573 defaultSelectValue := ssi.dynamicDeps.SelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey)
1574 (&defaultSelectValue).Append(bazel.MakeLabelList([]bazel.Label{ssi.impl}))
1575 ssi.dynamicDeps.SetSelectValue(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, bazel.FirstUniqueBazelLabelList(defaultSelectValue))
1576 }
Liz Kammere6583482021-10-19 13:56:10 -04001577}
1578
Yu Liu10174ff2023-02-21 12:05:26 -08001579func setStubsForDynamicDeps(ctx android.BazelConversionPathContext, axis bazel.ConfigurationAxis,
Spandan Dasac693b22023-04-24 00:07:38 +00001580 config string, apexAvailable []string, dynamicLibs bazel.LabelList, dynamicDeps *bazel.LabelListAttribute, ind int, buildNonApexWithStubs bool) {
Liz Kammer48cdbeb2023-03-17 10:17:50 -04001581
Spandan Das4242f102023-04-19 22:31:54 +00001582 // Create a config_setting for each apex_available.
1583 // This will be used to select impl of a dep if dep is available to the same apex.
1584 for _, aa := range apexAvailable {
1585 createInApexConfigSetting(ctx.(android.TopDownMutatorContext), aa)
1586 }
1587
Spandan Das6d4d9da2023-04-18 06:20:40 +00001588 apiDomainForSelects := []string{}
1589 for _, apex := range apexAvailable {
1590 apiDomainForSelects = append(apiDomainForSelects, GetApiDomain(apex))
1591 }
1592 // Always emit a select statement for the platform variant.
1593 // This ensures that b build //foo --config=android works
1594 // Soong always creates a platform variant even when the library might not be available to platform.
1595 if !android.InList(android.AvailableToPlatform, apiDomainForSelects) {
1596 apiDomainForSelects = append(apiDomainForSelects, android.AvailableToPlatform)
1597 }
1598 apiDomainForSelects = android.SortedUniqueStrings(apiDomainForSelects)
1599
1600 // Create a select for each apex this library could be included in.
1601 for _, l := range dynamicLibs.Includes {
1602 dep, _ := ctx.ModuleFromName(l.OriginalModuleName)
1603 if c, ok := dep.(*Module); !ok || !c.HasStubsVariants() {
1604 continue
1605 }
1606 // TODO (b/280339069): Decrease the verbosity of the generated BUILD files
1607 for _, apiDomain := range apiDomainForSelects {
1608 var sameApiDomain bool
1609 if apiDomain == android.AvailableToPlatform {
1610 // Platform variants in Soong use equality of apex_available for stub/impl selection.
1611 // https://cs.android.com/android/_/android/platform/build/soong/+/316b0158fe57ee7764235923e7c6f3d530da39c6:cc/cc.go;l=3393-3404;drc=176271a426496fa2688efe2b40d5c74340c63375;bpv=1;bpt=0
1612 // One of the factors behind this design choice is cc_test
1613 // Tests only have a platform variant, and using equality of apex_available ensures
1614 // that tests of an apex library gets its implementation and not stubs.
1615 // TODO (b/280343104): Discuss if we can drop this special handling for platform variants.
1616 sameApiDomain = availableToSameApexes(apexAvailable, dep.(*Module).ApexAvailable())
Spandan Das6aaab9d2023-05-04 17:27:30 +00001617 if linkable, ok := ctx.Module().(LinkableInterface); ok && linkable.Bootstrap() {
1618 sameApiDomain = true
1619 }
Spandan Das6d4d9da2023-04-18 06:20:40 +00001620 } else {
1621 sameApiDomain = android.InList(apiDomain, dep.(*Module).ApexAvailable())
1622 }
1623 ssi := stubSelectionInfo{
1624 impl: l,
1625 axis: axis,
1626 config: config,
1627 apiDomain: apiDomain,
1628 dynamicDeps: dynamicDeps,
1629 sameApiDomain: sameApiDomain,
1630 }
1631 useStubOrImplInApexWithName(ssi)
1632 }
1633 }
Yu Liu10174ff2023-02-21 12:05:26 -08001634}
1635
Jingwen Chen55bc8202021-11-02 06:40:51 +00001636func (la *linkerAttributes) convertStripProps(ctx android.BazelConversionPathContext, module *Module) {
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001637 bp2BuildPropParseHelper(ctx, module, &StripProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1638 if stripProperties, ok := props.(*StripProperties); ok {
1639 la.stripKeepSymbols.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols)
1640 la.stripKeepSymbolsList.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_list)
1641 la.stripKeepSymbolsAndDebugFrame.SetSelectValue(axis, config, stripProperties.Strip.Keep_symbols_and_debug_frame)
1642 la.stripAll.SetSelectValue(axis, config, stripProperties.Strip.All)
1643 la.stripNone.SetSelectValue(axis, config, stripProperties.Strip.None)
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001644 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001645 })
Liz Kammere6583482021-10-19 13:56:10 -04001646}
Jingwen Chen3d383bb2021-06-09 07:18:37 +00001647
Jingwen Chen55bc8202021-11-02 06:40:51 +00001648func (la *linkerAttributes) convertProductVariables(ctx android.BazelConversionPathContext, productVariableProps android.ProductConfigProperties) {
Jingwen Chen6ada5892021-09-17 11:38:09 +00001649
Liz Kammer47535c52021-06-02 16:02:22 -04001650 type productVarDep struct {
1651 // the name of the corresponding excludes field, if one exists
1652 excludesField string
1653 // reference to the bazel attribute that should be set for the given product variable config
1654 attribute *bazel.LabelListAttribute
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001655
Jingwen Chen55bc8202021-11-02 06:40:51 +00001656 depResolutionFunc func(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList
Liz Kammer47535c52021-06-02 16:02:22 -04001657 }
1658
Zi Wang0a8a1292022-08-30 06:27:01 +00001659 // an intermediate attribute that holds Header_libs info, and will be appended to
1660 // implementationDeps at the end, to solve the confliction that both header_libs
1661 // and static_libs use implementationDeps.
1662 var headerDeps bazel.LabelListAttribute
1663
Liz Kammer47535c52021-06-02 16:02:22 -04001664 productVarToDepFields := map[string]productVarDep{
1665 // product variables do not support exclude_shared_libs
Jingwen Chen55bc8202021-11-02 06:40:51 +00001666 "Shared_libs": {attribute: &la.implementationDynamicDeps, depResolutionFunc: bazelLabelForSharedDepsExcludes},
1667 "Static_libs": {"Exclude_static_libs", &la.implementationDeps, bazelLabelForStaticDepsExcludes},
1668 "Whole_static_libs": {"Exclude_static_libs", &la.wholeArchiveDeps, bazelLabelForWholeDepsExcludes},
Zi Wang0a8a1292022-08-30 06:27:01 +00001669 "Header_libs": {attribute: &headerDeps, depResolutionFunc: bazelLabelForHeaderDepsExcludes},
Liz Kammer47535c52021-06-02 16:02:22 -04001670 }
1671
Liz Kammer47535c52021-06-02 16:02:22 -04001672 for name, dep := range productVarToDepFields {
1673 props, exists := productVariableProps[name]
1674 excludeProps, excludesExists := productVariableProps[dep.excludesField]
Sasha Smundak39a301c2022-12-29 17:11:49 -08001675 // if neither an include nor excludes property exists, then skip it
Liz Kammer47535c52021-06-02 16:02:22 -04001676 if !exists && !excludesExists {
1677 continue
1678 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001679 // Collect all the configurations that an include or exclude property exists for.
1680 // We want to iterate all configurations rather than either the include or exclude because, for a
1681 // particular configuration, we may have either only an include or an exclude to handle.
Cole Faust150f9a52023-04-26 10:52:24 -07001682 productConfigProps := make(map[android.ProductConfigOrSoongConfigProperty]bool, len(props)+len(excludeProps))
Jingwen Chen25825ca2021-11-15 12:28:43 +00001683 for p := range props {
1684 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001685 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001686 for p := range excludeProps {
1687 productConfigProps[p] = true
Liz Kammer47535c52021-06-02 16:02:22 -04001688 }
1689
Jingwen Chen25825ca2021-11-15 12:28:43 +00001690 for productConfigProp := range productConfigProps {
1691 prop, includesExists := props[productConfigProp]
1692 excludesProp, excludesExists := excludeProps[productConfigProp]
Liz Kammer47535c52021-06-02 16:02:22 -04001693 var includes, excludes []string
1694 var ok bool
1695 // if there was no includes/excludes property, casting fails and that's expected
Jingwen Chen25825ca2021-11-15 12:28:43 +00001696 if includes, ok = prop.([]string); includesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001697 ctx.ModuleErrorf("Could not convert product variable %s property", name)
1698 }
Jingwen Chen25825ca2021-11-15 12:28:43 +00001699 if excludes, ok = excludesProp.([]string); excludesExists && !ok {
Liz Kammer47535c52021-06-02 16:02:22 -04001700 ctx.ModuleErrorf("Could not convert product variable %s property", dep.excludesField)
1701 }
Liz Kammer2d7bbe32021-06-10 18:20:06 -04001702
Jingwen Chen58ff6802021-11-17 12:14:41 +00001703 dep.attribute.EmitEmptyList = productConfigProp.AlwaysEmit()
Jingwen Chen25825ca2021-11-15 12:28:43 +00001704 dep.attribute.SetSelectValue(
1705 productConfigProp.ConfigurationAxis(),
1706 productConfigProp.SelectKey(),
1707 dep.depResolutionFunc(ctx, android.FirstUniqueStrings(includes), excludes),
1708 )
Liz Kammer47535c52021-06-02 16:02:22 -04001709 }
1710 }
Zi Wang0a8a1292022-08-30 06:27:01 +00001711 la.implementationDeps.Append(headerDeps)
Liz Kammere6583482021-10-19 13:56:10 -04001712}
Liz Kammer47535c52021-06-02 16:02:22 -04001713
Liz Kammer54309532021-12-14 12:21:22 -05001714func (la *linkerAttributes) finalize(ctx android.BazelConversionPathContext) {
1715 // if system dynamic deps have the default value, any use of a system dynamic library used will
1716 // result in duplicate library errors for bionic OSes. Here, we explicitly exclude those libraries
Liz Kammer43345e22022-08-04 13:57:35 -04001717 // from bionic OSes and the no config case as these libraries only build for bionic OSes.
Liz Kammer54309532021-12-14 12:21:22 -05001718 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsDynamicDep) > 0 {
Cole Faust18994c72023-02-28 16:02:16 -08001719 toRemove := bazelLabelForSharedDeps(ctx, android.SortedKeys(la.usedSystemDynamicDepAsDynamicDep))
Liz Kammer43345e22022-08-04 13:57:35 -04001720 la.dynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001721 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1722 la.dynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001723 la.implementationDynamicDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
Liz Kammer54309532021-12-14 12:21:22 -05001724 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1725 la.implementationDynamicDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001726
1727 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.ConditionsDefaultConfigKey, toRemove)
Liz Kammer91487d42022-09-13 11:27:11 -04001728 stubsToRemove := make([]bazel.Label, 0, len(la.usedSystemDynamicDepAsDynamicDep))
1729 for _, lib := range toRemove.Includes {
Spandan Das2518c022023-03-17 03:02:32 +00001730 stubLabelInApiSurfaces := bazel.Label{
1731 Label: apiSurfaceModuleLibCurrentPackage + lib.OriginalModuleName,
1732 }
1733 stubsToRemove = append(stubsToRemove, stubLabelInApiSurfaces)
Liz Kammer91487d42022-09-13 11:27:11 -04001734 }
Spandan Das6d4d9da2023-04-18 06:20:40 +00001735 // system libraries (e.g. libc, libm, libdl) belong the com.android.runtime api domain
1736 // dedupe the stubs of these libraries from the other api domains (platform, other_apexes...)
1737 for _, aa := range ctx.Module().(*Module).ApexAvailable() {
1738 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, inApexConfigSetting(aa), bazel.MakeLabelList(stubsToRemove))
1739 }
1740 la.implementationDynamicDeps.Exclude(bazel.OsAndInApexAxis, bazel.AndroidPlatform, bazel.MakeLabelList(stubsToRemove))
Liz Kammer54309532021-12-14 12:21:22 -05001741 }
Liz Kammerb4928432023-06-02 18:43:36 -04001742 if la.systemDynamicDeps.IsNil() && len(la.usedSystemDynamicDepAsStaticDep) > 0 {
1743 toRemove := bazelLabelForStaticDeps(ctx, android.SortedKeys(la.usedSystemDynamicDepAsStaticDep))
1744 la.deps.Exclude(bazel.NoConfigAxis, "", toRemove)
1745 la.deps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1746 la.deps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
1747 la.implementationDeps.Exclude(bazel.NoConfigAxis, "", toRemove)
1748 la.implementationDeps.Exclude(bazel.OsConfigurationAxis, "android", toRemove)
1749 la.implementationDeps.Exclude(bazel.OsConfigurationAxis, "linux_bionic", toRemove)
1750 }
Liz Kammer54309532021-12-14 12:21:22 -05001751
Liz Kammere6583482021-10-19 13:56:10 -04001752 la.deps.ResolveExcludes()
1753 la.implementationDeps.ResolveExcludes()
1754 la.dynamicDeps.ResolveExcludes()
1755 la.implementationDynamicDeps.ResolveExcludes()
1756 la.wholeArchiveDeps.ResolveExcludes()
1757 la.systemDynamicDeps.ForceSpecifyEmptyList = true
Liz Kammer54309532021-12-14 12:21:22 -05001758
Jingwen Chen91220d72021-03-24 02:18:33 -04001759}
1760
Jingwen Chened9c17d2021-04-13 07:14:55 +00001761// Relativize a list of root-relative paths with respect to the module's
1762// directory.
1763//
1764// include_dirs Soong prop are root-relative (b/183742505), but
1765// local_include_dirs, export_include_dirs and export_system_include_dirs are
1766// module dir relative. This function makes a list of paths entirely module dir
1767// relative.
1768//
1769// For the `include` attribute, Bazel wants the paths to be relative to the
1770// module.
1771func bp2BuildMakePathsRelativeToModule(ctx android.BazelConversionPathContext, paths []string) []string {
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001772 var relativePaths []string
1773 for _, path := range paths {
Jingwen Chened9c17d2021-04-13 07:14:55 +00001774 // Semantics of filepath.Rel: join(ModuleDir, rel(ModuleDir, path)) == path
1775 relativePath, err := filepath.Rel(ctx.ModuleDir(), path)
1776 if err != nil {
1777 panic(err)
1778 }
Rupert Shuttleworthb8151682021-04-06 20:06:21 +00001779 relativePaths = append(relativePaths, relativePath)
1780 }
1781 return relativePaths
1782}
1783
Liz Kammer5fad5012021-09-09 14:08:21 -04001784// BazelIncludes contains information about -I and -isystem paths from a module converted to Bazel
1785// attributes.
1786type BazelIncludes struct {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001787 AbsoluteIncludes bazel.StringListAttribute
1788 Includes bazel.StringListAttribute
1789 SystemIncludes bazel.StringListAttribute
Liz Kammer5fad5012021-09-09 14:08:21 -04001790}
1791
Liz Kammer54549442022-05-11 13:55:06 -04001792func bp2BuildParseExportedIncludes(ctx android.BazelConversionPathContext, module *Module, includes *BazelIncludes) BazelIncludes {
Liz Kammer1263d9b2021-12-10 14:28:20 -05001793 var exported BazelIncludes
1794 if includes != nil {
1795 exported = *includes
1796 } else {
1797 exported = BazelIncludes{}
1798 }
Zi Wang1cb11802022-12-09 16:08:54 -08001799
1800 // cc library Export_include_dirs and Export_system_include_dirs are marked
1801 // "variant_prepend" in struct tag, set their prepend property to true to make
1802 // sure bp2build generates correct result.
1803 exported.Includes.Prepend = true
1804 exported.SystemIncludes.Prepend = true
1805
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001806 bp2BuildPropParseHelper(ctx, module, &FlagExporterProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1807 if flagExporterProperties, ok := props.(*FlagExporterProperties); ok {
1808 if len(flagExporterProperties.Export_include_dirs) > 0 {
1809 exported.Includes.SetSelectValue(axis, config, android.FirstUniqueStrings(append(exported.Includes.SelectValue(axis, config), flagExporterProperties.Export_include_dirs...)))
1810 }
1811 if len(flagExporterProperties.Export_system_include_dirs) > 0 {
1812 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 -04001813 }
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001814 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001815 })
Liz Kammer1263d9b2021-12-10 14:28:20 -05001816 exported.AbsoluteIncludes.DeduplicateAxesFromBase()
Liz Kammer5fad5012021-09-09 14:08:21 -04001817 exported.Includes.DeduplicateAxesFromBase()
1818 exported.SystemIncludes.DeduplicateAxesFromBase()
Rupert Shuttleworth375451e2021-04-26 07:49:08 -04001819
Liz Kammer5fad5012021-09-09 14:08:21 -04001820 return exported
Jingwen Chen91220d72021-03-24 02:18:33 -04001821}
Chris Parsons953b3562021-09-20 15:14:39 -04001822
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001823func BazelLabelNameForStaticModule(baseLabel string) string {
1824 return baseLabel + "_bp2build_cc_library_static"
1825}
1826
Jingwen Chen55bc8202021-11-02 06:40:51 +00001827func bazelLabelForStaticModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001828 label := android.BazelModuleLabel(ctx, m)
Sasha Smundak39a301c2022-12-29 17:11:49 -08001829 if ccModule, ok := m.(*Module); ok && ccModule.typ() == fullLibrary {
Trevor Radcliffecee4e052022-09-06 19:31:25 +00001830 return BazelLabelNameForStaticModule(label)
Chris Parsons953b3562021-09-20 15:14:39 -04001831 }
1832 return label
1833}
1834
Jingwen Chen55bc8202021-11-02 06:40:51 +00001835func bazelLabelForSharedModule(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001836 // cc_library, at it's root name, propagates the shared library, which depends on the static
1837 // library.
1838 return android.BazelModuleLabel(ctx, m)
1839}
1840
Jingwen Chen55bc8202021-11-02 06:40:51 +00001841func bazelLabelForStaticWholeModuleDeps(ctx android.BazelConversionPathContext, m blueprint.Module) string {
Chris Parsons953b3562021-09-20 15:14:39 -04001842 label := bazelLabelForStaticModule(ctx, m)
1843 if aModule, ok := m.(android.Module); ok {
1844 if android.IsModulePrebuilt(aModule) {
1845 label += "_alwayslink"
1846 }
1847 }
1848 return label
1849}
1850
Liz Kammer5f5dbaa2023-07-17 17:44:08 -04001851func xsdConfigCppTarget(xsd android.XsdConfigBp2buildTargets) string {
1852 return xsd.CppBp2buildTargetName()
Liz Kammer084d6a92023-06-22 16:23:53 -04001853}
1854
Jingwen Chen55bc8202021-11-02 06:40:51 +00001855func bazelLabelForWholeDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001856 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticWholeModuleDeps)
1857}
1858
Jingwen Chen55bc8202021-11-02 06:40:51 +00001859func bazelLabelForWholeDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001860 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticWholeModuleDeps)
1861}
1862
Jingwen Chen55bc8202021-11-02 06:40:51 +00001863func bazelLabelForStaticDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001864 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForStaticModule)
1865}
1866
Jingwen Chen55bc8202021-11-02 06:40:51 +00001867func bazelLabelForStaticDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001868 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForStaticModule)
1869}
1870
Jingwen Chen55bc8202021-11-02 06:40:51 +00001871func bazelLabelForSharedDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001872 return android.BazelLabelForModuleDepsWithFn(ctx, modules, bazelLabelForSharedModule)
1873}
1874
Jingwen Chen55bc8202021-11-02 06:40:51 +00001875func bazelLabelForHeaderDeps(ctx android.BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001876 // This is not elegant, but bp2build's shared library targets only propagate
1877 // their header information as part of the normal C++ provider.
1878 return bazelLabelForSharedDeps(ctx, modules)
1879}
1880
Zi Wang0a8a1292022-08-30 06:27:01 +00001881func bazelLabelForHeaderDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
1882 // This is only used when product_variable header_libs is processed, to follow
1883 // the pattern of depResolutionFunc
1884 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1885}
1886
Jingwen Chen55bc8202021-11-02 06:40:51 +00001887func bazelLabelForSharedDepsExcludes(ctx android.BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -04001888 return android.BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, bazelLabelForSharedModule)
1889}
Liz Kammer2b8004b2021-10-04 13:55:44 -04001890
1891type binaryLinkerAttrs struct {
1892 Linkshared *bool
Spandan Das39ccf932023-05-26 18:03:39 +00001893 Stem bazel.StringAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001894 Suffix bazel.StringAttribute
Liz Kammer2b8004b2021-10-04 13:55:44 -04001895}
1896
Jingwen Chen55bc8202021-11-02 06:40:51 +00001897func bp2buildBinaryLinkerProps(ctx android.BazelConversionPathContext, m *Module) binaryLinkerAttrs {
Liz Kammer2b8004b2021-10-04 13:55:44 -04001898 attrs := binaryLinkerAttrs{}
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001899 bp2BuildPropParseHelper(ctx, m, &BinaryLinkerProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1900 linkerProps := props.(*BinaryLinkerProperties)
1901 staticExecutable := linkerProps.Static_executable
1902 if axis == bazel.NoConfigAxis {
1903 if linkBinaryShared := !proptools.Bool(staticExecutable); !linkBinaryShared {
1904 attrs.Linkshared = &linkBinaryShared
Liz Kammer2b8004b2021-10-04 13:55:44 -04001905 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001906 } else if staticExecutable != nil {
1907 // TODO(b/202876379): Static_executable is arch-variant; however, linkshared is a
1908 // nonconfigurable attribute. Only 4 AOSP modules use this feature, defer handling
1909 ctx.ModuleErrorf("bp2build cannot migrate a module with arch/target-specific static_executable values")
Liz Kammer2b8004b2021-10-04 13:55:44 -04001910 }
Spandan Das39ccf932023-05-26 18:03:39 +00001911 if stem := linkerProps.Stem; stem != nil {
1912 attrs.Stem.SetSelectValue(axis, config, stem)
1913 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxa56e9702022-02-23 18:39:59 -05001914 if suffix := linkerProps.Suffix; suffix != nil {
1915 attrs.Suffix.SetSelectValue(axis, config, suffix)
1916 }
Trevor Radcliffe542954f2022-04-21 20:04:42 +00001917 })
Liz Kammer2b8004b2021-10-04 13:55:44 -04001918
1919 return attrs
1920}
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001921
Trevor Radcliffed9b7f172023-08-09 22:21:38 +00001922type sanitizerValues struct {
1923 features bazel.StringListAttribute
1924 copts bazel.StringListAttribute
1925 additionalCompilerInputs bazel.LabelListAttribute
1926}
1927
1928func bp2buildSanitizerFeatures(ctx android.BazelConversionPathContext, m *Module) sanitizerValues {
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001929 sanitizerFeatures := bazel.StringListAttribute{}
Trevor Radcliffed9b7f172023-08-09 22:21:38 +00001930 sanitizerCopts := bazel.StringListAttribute{}
1931 sanitizerCompilerInputs := bazel.LabelListAttribute{}
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001932 bp2BuildPropParseHelper(ctx, m, &SanitizeProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1933 var features []string
1934 if sanitizerProps, ok := props.(*SanitizeProperties); ok {
1935 if sanitizerProps.Sanitize.Integer_overflow != nil && *sanitizerProps.Sanitize.Integer_overflow {
1936 features = append(features, "ubsan_integer_overflow")
1937 }
1938 for _, sanitizer := range sanitizerProps.Sanitize.Misc_undefined {
1939 features = append(features, "ubsan_"+sanitizer)
1940 }
Trevor Radcliffeded095c2023-06-12 19:18:28 +00001941 blocklist := sanitizerProps.Sanitize.Blocklist
1942 if blocklist != nil {
Trevor Radcliffed9b7f172023-08-09 22:21:38 +00001943 // TODO: b/294868620 - Change this not to use the special axis when completing the bug
1944 coptValue := fmt.Sprintf("-fsanitize-ignorelist=$(location %s)", *blocklist)
1945 sanitizerCopts.SetSelectValue(bazel.SanitizersEnabledAxis, bazel.SanitizersEnabled, []string{coptValue})
1946 sanitizerCompilerInputs.SetSelectValue(bazel.SanitizersEnabledAxis, bazel.SanitizersEnabled, bazel.MakeLabelListFromTargetNames([]string{*blocklist}))
Trevor Radcliffeded095c2023-06-12 19:18:28 +00001947 }
Trevor Radcliffe523c5c62023-06-16 20:15:45 +00001948 if sanitizerProps.Sanitize.Cfi != nil && !proptools.Bool(sanitizerProps.Sanitize.Cfi) {
1949 features = append(features, "-android_cfi")
1950 } else if proptools.Bool(sanitizerProps.Sanitize.Cfi) {
Trevor Radcliffe27669c02023-03-28 20:47:10 +00001951 features = append(features, "android_cfi")
1952 if proptools.Bool(sanitizerProps.Sanitize.Config.Cfi_assembly_support) {
1953 features = append(features, "android_cfi_assembly_support")
1954 }
1955 }
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001956 sanitizerFeatures.SetSelectValue(axis, config, features)
1957 }
1958 })
Trevor Radcliffed9b7f172023-08-09 22:21:38 +00001959 return sanitizerValues{
1960 features: sanitizerFeatures,
1961 copts: sanitizerCopts,
1962 additionalCompilerInputs: sanitizerCompilerInputs,
1963 }
Trevor Radcliffedb7e0262022-10-28 16:48:18 +00001964}
Trevor Radcliffe56b1a2b2023-02-06 21:58:30 +00001965
1966func bp2buildLtoFeatures(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
1967 lto_feature_name := "android_thin_lto"
1968 ltoBoolFeatures := bazel.BoolAttribute{}
1969 bp2BuildPropParseHelper(ctx, m, &LTOProperties{}, func(axis bazel.ConfigurationAxis, config string, props interface{}) {
1970 if ltoProps, ok := props.(*LTOProperties); ok {
1971 thinProp := ltoProps.Lto.Thin != nil && *ltoProps.Lto.Thin
1972 thinPropSetToFalse := ltoProps.Lto.Thin != nil && !*ltoProps.Lto.Thin
1973 neverProp := ltoProps.Lto.Never != nil && *ltoProps.Lto.Never
1974 if thinProp {
1975 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(true))
1976 return
1977 }
1978 if neverProp || thinPropSetToFalse {
1979 if thinProp {
1980 ctx.ModuleErrorf("lto.thin and lto.never are mutually exclusive but were specified together")
1981 } else {
1982 ltoBoolFeatures.SetSelectValue(axis, config, BoolPtr(false))
1983 }
1984 return
1985 }
1986 }
1987 ltoBoolFeatures.SetSelectValue(axis, config, nil)
1988 })
1989
1990 props := m.GetArchVariantProperties(ctx, &LTOProperties{})
1991 ltoStringFeatures, err := ltoBoolFeatures.ToStringListAttribute(func(boolPtr *bool, axis bazel.ConfigurationAxis, config string) []string {
1992 if boolPtr == nil {
1993 return []string{}
1994 }
1995 if !*boolPtr {
1996 return []string{"-" + lto_feature_name}
1997 }
1998 features := []string{lto_feature_name}
1999 if ltoProps, ok := props[axis][config].(*LTOProperties); ok {
2000 if ltoProps.Whole_program_vtables != nil && *ltoProps.Whole_program_vtables {
2001 features = append(features, "android_thin_lto_whole_program_vtables")
2002 }
2003 }
2004 return features
2005 })
2006 if err != nil {
2007 ctx.ModuleErrorf("Error processing LTO attributes: %s", err)
2008 }
2009 return ltoStringFeatures
2010}
Trevor Radcliffea8b44162023-04-14 18:25:24 +00002011
2012func convertHiddenVisibilityToFeatureBase(ctx android.BazelConversionPathContext, m *Module) bazel.StringListAttribute {
2013 visibilityHiddenFeature := bazel.StringListAttribute{}
2014 bp2BuildPropParseHelper(ctx, m, &BaseCompilerProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
2015 if baseCompilerProps, ok := props.(*BaseCompilerProperties); ok {
2016 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, baseCompilerProps.Cflags)
2017 }
2018 })
2019 return visibilityHiddenFeature
2020}
2021
2022func convertHiddenVisibilityToFeatureStaticOrShared(ctx android.BazelConversionPathContext, m *Module, isStatic bool) bazel.StringListAttribute {
2023 visibilityHiddenFeature := bazel.StringListAttribute{}
2024 if isStatic {
2025 bp2BuildPropParseHelper(ctx, m, &StaticProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
2026 if staticProps, ok := props.(*StaticProperties); ok {
2027 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, staticProps.Static.Cflags)
2028 }
2029 })
2030 } else {
2031 bp2BuildPropParseHelper(ctx, m, &SharedProperties{}, func(axis bazel.ConfigurationAxis, configString string, props interface{}) {
2032 if sharedProps, ok := props.(*SharedProperties); ok {
2033 convertHiddenVisibilityToFeatureHelper(&visibilityHiddenFeature, axis, configString, sharedProps.Shared.Cflags)
2034 }
2035 })
2036 }
2037
2038 return visibilityHiddenFeature
2039}
2040
2041func convertHiddenVisibilityToFeatureHelper(feature *bazel.StringListAttribute, axis bazel.ConfigurationAxis, configString string, cflags []string) {
2042 if inList(config.VisibilityHiddenFlag, cflags) {
2043 feature.SetSelectValue(axis, configString, []string{"visibility_hidden"})
2044 }
2045}